unity项目--控制相机跟随

9 篇文章 0 订阅
本文介绍了在Unity中控制玩家移动(使用Rigidbody和按键事件)以及如何通过脚本使相机跟随玩家并切换至第一人称视角。
摘要由CSDN通过智能技术生成

最开始用float进行表示浮点型,上一章写了输入,关于属于放在update里,物理类型的放在Fixedupdate里。

bool布尔类型,布尔值判断是否即对错。

update里先初始化,左键用a,右键用d


using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
   public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sideWaysForce = 500f;
    bool leftPressed;//布尔值判断是否
    bool rightPressed;

    void Start()
    {
      
    }

    
    void Update()//每帧都运行,输入部分放置在这里
    {
        leftPressed = Input.GetKey("a");
        rightPressed= Input.GetKey("d");
    }
    private void FixedUpdate()//物理类型
    {
        rb.AddForce(0,0, forwardForce*Time.deltaTime);//均衡不同电脑帧率
        if (Input.GetKey("d"))
        {
            rb.AddForce(sideWaysForce* Time.deltaTime, 0, 0);
        }
        if (Input.GetKey("a"))
        {
            rb.AddForce(-sideWaysForce * Time.deltaTime, 0, 0);
        }
    }
    
}

操作相机

可以将相机直接拖到player里边,就可以看见相机跟着player一起移动,但是会随着物体旋转而旋转。那么我们使用脚本控制是最好的解决方式。

在scripts里创建一个c#命名为Followplayer,拖到相机的数值界面

每一帧都要跟着player,先公开一个变量

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowPlayer : MonoBehaviour//CLASS类名
{
    public Transform player;
    
    void Start()
    {
        
    }

  
    void Update()
    {
        transform.position=player.position;
    }
}

用脚本将player引进去。变成第一人称视角。

再引入一个变量添加一个偏移量.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowPlayer : MonoBehaviour//CLASS类名
{
    public Transform player;
    public Vector3 offset;//偏移
    void Start()
    {
        
    }

  
    void Update()
    {
        transform.position=player.position+offset;
    }
}

将相机的位置进行调整,能更好的观察到物体移动。

此时调整后就不再是第一视角。可以自己调整合适的位置。将player1也放出来可以做一个参照物。

今天先到这里,明天接着更新......

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值