使用C#在Unity 3D中进行车轮转向
本文关键字:Unity 3D 使用 | 更新日期: 2023-09-27 18:20:50
我对C#中的脚本编写还很陌生,而且我已经被这个问题困扰了好几天了。我制作了这个脚本,这样我的车就可以在地图上移动,车轮在Z轴上旋转。脚本:
using UnityEngine;
using System.Collections;
public class CarMovement : MonoBehaviour
{
public Transform wheelFLTrans;
public Transform wheelFRTrans;
public Transform wheelBRTrans;
public Transform wheelBLTrans;
public float MotorForce;
public float Steerforce;
public WheelCollider GumaPD;
public WheelCollider GumaPLj;
public WheelCollider GumaZD;
public WheelCollider GumaZLJ;
void Start()
{
}
// Update is called once per frame
void Update()
{
float v = Input.GetAxis("Vertical") * MotorForce;
float h = Input.GetAxis("Horizontal") * Steerforce;
GumaPD.motorTorque = v;
GumaPLj.motorTorque = v;
GumaPD.steerAngle = h;
GumaPLj.steerAngle = h;
wheelFLTrans.Rotate(Vector3.forward * GumaPLj.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
wheelFRTrans.Rotate(Vector3.forward * GumaPD.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
wheelBRTrans.Rotate(Vector3.forward * GumaZD.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
wheelBLTrans.Rotate(Vector3.forward * GumaZLJ.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
wheelFRTrans.eulerAngles = new Vector3(0f, Input.GetAxis("Horizontal"), 0f);
}
}
现在我的问题是:
当我开车穿过地图时,我想增加方向盘。就像当我按下A或D键时,车轮会根据我按下的键(A或D)转向。我试过使用这行代码:
**wheelFRTrans.localEulerAngles = new Vector3(0, wheelFR.steerAngle, 0);**
这是有效的,但后来由于某种原因,我的前轮停止转动:(.有人能帮我解决这个问题吗?我已经被这个问题困扰了好几天了:(.我希望我的车轮能同时转动和转向:/.
我很抱歉我的英语不好。
谢谢!
我解决了问题:
Tires[0].transform.Rotate(Vector3.right,-BLWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
Tires[1].transform.Rotate(Vector3.right,BRWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
Tires[2].transform.Rotate(Vector3.right, FLWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
Tires[3].transform.Rotate(Vector3.right, -FRWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
Tires[2].transform.Rotate(Vector3.up, FLWheel.steerAngle - tempAngle,Space.World);
Tires[3].transform.Rotate(Vector3.up, FLWheel.steerAngle - tempAngle,Space.World);
tempAngle = FLWheel.steerAngle;