【Unity】 实现角色移动、视角旋转以及跳跃

【Unity】 实现角色移动、视角旋转以及跳跃

一、使用UGUI创建角色模型和地面

创建一个Capsule和一个Cube模型,将其放在空物体下面,命名为Player
在这里插入图片描述
创建一个Plane作为地面

二、在【Inspector】面板中调整Player属性

Player中添加RigidbodyCapsuleCollider组件
Transform中修改Position,将Y改为1
Rigidbody -> Constraints -> FreezeRotaion中勾选 X Y Z
CapsuleCollider中将Height属性改为2
在这里插入图片描述

三、为Player添加移动代码

添加PlayerContoller脚本,并拖拽到Player上,具体代码如下

Transform cameraObj;
Vector3 moveDirection;
Rigidbody rb;
//初始化
void Awake()
{
    
    
    cameraObj = Camera.main.transform;
    rb=GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
    
    
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");

    moveDirection= cameraObj.forward*v;
    moveDirection+=cameraObj.right*h;
    moveDirection.Normalize();//归一化
    moveDirection *= 5f;//移动速度设定为5f
    moveDirection.y = 0f;//防止Player运动时倾斜
}
//物理更新
void FixedUpdate()
{
    
    
    rb.velocity = moveDirection;
}

运行效果如下
在这里插入图片描述
在Update中添加物体转向代码,旋转速度为0.3f

transform.forward = Vector3.Slerp(transform.forward, moveDirection, 0.3f);

在这里插入图片描述
此时物体在移动的过程中的朝向问题就解决了

四、添加角色跳跃

声明一个跳跃高度变量的

float jumpHeight;

在Awake下初始化jumpHeight

jumpHeight = 0;

调整FixedUpdate中的代码

rb.velocity = new Vector3(moveDirection.x, rb.velocity.y, moveDirection.z) + Vector3.up * jumpHeight;
jumpHeight = 0f;//初始化跳跃高度

添加跳跃方法

void Jump()
{
    
    
    jumpHeight = 5f;
}

在Update中添加键盘事件,当按下空格时触发跳跃

if (Input.GetKeyDown(KeyCode.Space))
{
    
    
    Jump();
}

在这里插入图片描述

恭喜你完成了本次教学,后续更新的文章多多支持

猜你喜欢

转载自blog.csdn.net/weixin_44792145/article/details/128704397