unity开发罗技G29方向盘(制作操作汽车)
unity引擎结合罗技G29可驾驶车辆(操控性赛车游戏制作)
一:软硬件准备**
1、unity官网下载unity引擎(版本自选,作者使用2018.2.6)
2、罗技G29方向盘
3、罗技官方插件(根据自己电脑操作系统选择相应位数):https://support.logitech.com.cn/zh_cn/downloads
二、场景搭建
打开unity,新建项目并添加场景所需要的模型对汽车模型进行整理分离出所需要的关键模型,在四个车轮物体下建一个空物体然后将它们拖拽到WheelCollider下如下图所示:(汽车模型可以在unity Asset Store上下载)
为civilian_car_gray汽车添加物理刚体组件,使汽车受到物理作用力,并为WheelCollider下的空物体添加WheelCollider组件,调整车轮碰撞器的半径和位置(半径和位置根据自己实际操作调整)。
如果汽车模型没有碰撞器则需要对Body部分添加Box Collider组件,调整BocCollider组件大小和位置。到这里我们已经准本好了后期所需要的
如果觉得对汽车模型整理还有问题的可以参考我为大家推荐的一篇文章:(引用)
https://jingyan.baidu.com/article/1e5468f9620a50484961b7e7.html
三、Logitech驱动以及unity引擎配置
链接罗技G29方向盘后再驱动中使用默认通用按键配置
回到unity,打开Edit>>Project Settings>>Input,设置所需要的罗技按键
方向盘:
离合:
油门:
刹车:
档位:一档、二挡设置,后面其他档位改变Positive Button即可
说明:在对按键进行配置的时候根据实际按键为准,本文配置按键是和方向盘上显示不一致的。
参考文章:https://blog.****.net/baozaodedianxiaoer/article/details/80134658
四、代码交互
交互代码如下:
public class CarControl : MonoBehaviour
{
public WheelCollider[] wheelCollider;//车轮碰撞器
public Transform[] wheelObject;//车轮
public Rigidbody carRigidbody;//物理组件
int steerMaxAngle;//前轮最大转向角度
private int Power=600;//汽车动力
private int backPowe=25000;//汽车制动力
private void Awake()
{
//设置汽车重心,前轮最大转角
carRigidbody = transform.GetComponent<Rigidbody>();
carRigidbody.centerOfMass = new Vector3(carRigidbody.centerOfMass.x, 0.1f, carRigidbody.centerOfMass.z);
steerMaxAngle = 30;
}
void Update()
{
WheelRender();
CarGo();
}
void WheelRender()
{
//渲染车轮和车轮碰撞器一起运动
for (int count = 0; count < 4; count++)
{
Quaternion root;
Vector3 pos;
wheelCollider[count].GetWorldPose(out pos, out root);
wheelObject[count].position = pos;
wheelObject[count].rotation = root;
}
//设置汽车前轮转向、驱动、制动
float h = Input.GetAxisRaw("Horizontal");
float youmen = Input.GetAxisRaw("YouMen")+1;
float shache = Input.GetAxisRaw("ShaChe")+1;
Debug.Log(shache);
wheelCollider[0].steerAngle = wheelCollider[1].steerAngle = h * steerMaxAngle;
wheelCollider[2].motorTorque = wheelCollider[3].motorTorque = Power * youmen;
wheelCollider[2].brakeTorque = wheelCollider[3].brakeTorque = backPowe * shache;
}
}
将个物体拖拽到相应位置,运行项目,就可以使用罗技方向盘驾驶汽车了
说明:文中按键配置和车轮碰撞器创建受模型和引擎等因素影响,本文数据只做参考。