unity控制刚体移动旋转

刚体移动

看注释,很详细

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

public class TankMove : MonoBehaviour
{
	//刚体组件
    private Rigidbody _mRigidbody;
	//移动速度
    private float _speed = 5;

    // Start is called before the first frame update
    void Start()
    {
    	//得到物体的刚体组件
        _mRigidbody = GetComponent<Rigidbody>();
    }


    void FixedUpdate()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float vertiaclMovement = Input.GetAxis("Vertical");
        //刚体的移动 = transform.前后移动 * ws按键 * 自定义速度
        _mRigidbody.velocity = transform.forward * vertiaclMovement * _speed;
    }
}

刚体旋转

可以锁定刚体的旋转方向,在unity的刚体组件上
在这里插入图片描述
看注释

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

public class TankMove : MonoBehaviour
{
	//刚体组件
    private Rigidbody _mRigidbody;
	//旋转速度
    private float _angularSpeed = 10;
    // Start is called before the first frame update
    void Start()
    {
        _mRigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
    	//ad按键
        float horizontalMovement = Input.GetAxis("Horizontal");
		//刚体的旋转 = transform.z轴 * ad * 旋转速度
		//这里是要围绕z轴进行旋转
        _mRigidbody.angularVelocity = transform.up * horizontalMovement * _angularSpeed;
    }
}

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,关于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方法计算旋转的目标方向。您可以根据自己的需求进行调整和修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值