我试图让我的坦克朝老鼠面对的方向射击。目前坦克可以旋转看着鼠标,但我不知道如何让子弹去正确的方向!
目前顶部的炮塔旋转正确,我不确定那个物体上的旋转是否可以用于方向?
它是 unity 3d 但实际上是 2.5d 角度自上而下。
public class tankScript : MonoBehaviour
{
public float rotateSpeed = 90;
public float speed = 5.0f;
public float fireInterval = 0.5f;
public float bulletSpeed = 20;
public Transform spawnPoint;
public GameObject bulletObject;
float nextFire;
Camera cam;
Collider planecollider;
RaycastHit hit;
Ray ray;
Vector3 mouseDirection;
void Start()
{
nextFire = Time.time + fireInterval;
cam = GameObject.Find("Main Camera").GetComponent<Camera>();
planecollider = GameObject.Find("Plane").GetComponent<Collider>();
}
void Update()
{
var transAmount = speed * Time.deltaTime;
var rotateAmount = rotateSpeed * Time.deltaTime;
if (Input.GetKey("w"))
{
transform.Translate(0, 0, transAmount);
}
if (Input.GetKey("s"))
{
transform.Translate(0, 0, -transAmount);
}
if (Input.GetKey("a"))
{
transform.Rotate(0, -rotateAmount, 0);
}
if (Input.GetKey("d"))
{
transform.Rotate(0, rotateAmount, 0);
}
if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireInterval;
fire();
}
}
void fire()
{
ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider == planecollider)
{
mouseDirection = new Vector3(hit.point.x, 0.25f, hit.point.z);
float step = bulletSpeed * Time.deltaTime;
var bullet = Instantiate(bulletObject, spawnPoint.position, spawnPoint.rotation);
bullet.GetComponent<Rigidbody>().transform.localPosition = Vector3.MoveTowards(transform.localPosition, mouseDirection, step);
}
}
}