Unity3D-輪子碰撞器控制坦克移動的簡單示例
阿新 • • 發佈:2019-01-10
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerTanke : TankeBase { protected override void Start() { base.Start(); //隱藏滑鼠 Cursor.lockState = CursorLockMode.Locked; } private float hitDuring; private float xRotationAllSize;//炮臺沿著X軸旋轉總大小 protected override void Update() { base.Update(); float horizonta = Input.GetAxis("Horizontal"); float verticalValue = Input.GetAxis("Vertical"); //轉向 if (horizonta != 0) { wheel_colliders[0].steerAngle = horizonta * 50f; wheel_colliders[1].steerAngle = horizonta * 50f; } // Debug.Log("horizontalValue:" +(horizonta * 50f * Time.deltaTime)); //前進 if (verticalValue != 0) { wheel_colliders[2].motorTorque = verticalValue * 1000f; wheel_colliders[3].motorTorque = verticalValue * 1000f; AudioManager.Instance.PlaySound(move_sound); } //炮臺左右旋轉 旋轉Y軸 float mouseX = Input.GetAxis("Mouse X"); if (mouseX != 0 && turret != null) { turret.localEulerAngles += Vector3.up * mouseX * Time.deltaTime * 20;//每秒旋轉20度 } //炮臺上下旋轉 旋轉X軸 float mouseY = Input.GetAxis("Mouse Y"); if (mouseY != 0) { // turret.Rotate(Vector3.right * mouseY * Time.deltaTime * 5); //旋轉角度,限制在-45度 和20度之間 xRotationAllSize += -mouseY * 5 * Time.deltaTime; if (xRotationAllSize <= 20 && xRotationAllSize >= -45) { turret.Rotate(-mouseY * 5 * Time.deltaTime, 0, 0, Space.Self); } xRotationAllSize = Mathf.Clamp(xRotationAllSize, -45, 20); // xRotationAllSize += ; //turret.localEulerAngles += Vector3.left * mouseY * Time.deltaTime * 30; Debug.Log("xRotationAllSize:" + xRotationAllSize); } //開火 hitDuring += Time.deltaTime; if (hitDuring > 0.3f && Input.GetMouseButton(0)) { hitDuring = 0; Fire(); } //剎車 if (Input.GetMouseButton(1)) { wheel_colliders[0].brakeTorque = 3000f; wheel_colliders[1].brakeTorque = 3000f; wheel_colliders[2].brakeTorque = 3000f; wheel_colliders[3].brakeTorque = 3000f; } else { wheel_colliders[0].brakeTorque = 0; wheel_colliders[1].brakeTorque = 0; wheel_colliders[2].brakeTorque = 0; wheel_colliders[3].brakeTorque = 0; } } }