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;
    }
}

发布了167 篇原创文章 · 获赞 179 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/104633904