unity人物移动

创建物体,加上Character Controller的组件

要实现人物移动需要先获取输入

float x, y;
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");

移动逻辑

Vector3 move;
move = transform.right * x + transform.forward * y;
playercontroller.Move(move * speed * Time.deltaTime);

完整代码

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

public class playermove : MonoBehaviour
{
    public float speed = 5.0f;

    public CharacterController playercontroller;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float x, y;
        x = Input.GetAxis("Horizontal");
        y = Input.GetAxis("Vertical");

        Vector3 move;

        move = transform.right * x + transform.forward * y;

        playercontroller.Move(move * speed * Time.deltaTime);

    }
}

好的,关于Unity人物移动旋转的代码,可以参考下面的示例代码: ``` using UnityEngine; public class PlayerController : MonoBehaviour { public float moveSpeed = 5f; //移动速度 public float rotateSpeed = 60f; //旋转速度 private Rigidbody rb; //刚体组件 void Start() { rb = GetComponent<Rigidbody>(); //获取刚体组件 } void FixedUpdate() { //获取水平和垂直输入轴的值 float hAxis = Input.GetAxis("Horizontal"); float vAxis = Input.GetAxis("Vertical"); //计算移动方向,使用Transform.TransformDirection方法将输入值转换为世界坐标系中的方向 Vector3 moveDirection = transform.TransformDirection(new Vector3(hAxis, 0, vAxis)); //将移动方向乘以移动速度,得到刚体的移动速度 Vector3 moveVelocity = moveDirection * moveSpeed; //将刚体的速度设置为计算出来的移动速度 rb.velocity = moveVelocity; //如果有输入则旋转角色 if (hAxis != 0 || vAxis != 0) { //计算旋转方向 Vector3 rotateDirection = new Vector3(hAxis, 0, vAxis); //使用Quaternion.LookRotation方法计算旋转的目标方向 Quaternion targetRotation = Quaternion.LookRotation(rotateDirection); //使用Quaternion.RotateTowards方法进行旋转 rb.rotation = Quaternion.RotateTowards(rb.rotation, targetRotation, rotateSpeed * Time.fixedDeltaTime); } } } ``` 以上代码实现了一个简单的角色移动和旋转的功能,其中使用了Rigidbody组件来控制角色的移动和旋转,同时使用了Input.GetAxis方法获取输入轴的值,并使用Quaternion.LookRotation方法计算旋转的目标方向。您可以根据自己的需求进行调整和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值