[英]Unity3d, Shooting at mouse position
我正在创建一个简单的街机游戏,但是射击时遇到麻烦。 播放器将具有此视图。 我希望玩家从玩家角色的炮塔上的鼠标位置射击。
这是我的代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gunController : MonoBehaviour {
public float speed = 3f;
public float fireRate = 3f;
public float force = 10f;
public GameObject bulletPrefab;
public GameObject gunEnd;
private GameObject bullet;
private Camera mainCam;
private float distance = 50f;
private Vector3 mousePos;
private bulletController bc;
private bool canShoot = true;
private Vector3 aim;
void Start () {
mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
}
// Update is called once per frame
void Update () {
//Get mouse position. You need to call this every frame not just in start
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
//declare your aim by adding +10f to the local.z position of your turret. Not 50f, because if your
//car goes past 50f then it'll start shooting behind
aim = new Vector3(mousePos.x, mousePos.y, transform.localPosition.z+10f);
//rotate turret to mouse
//now make turret look at your aim not your mousePos - you want it to look at an X Y Z point, not X Y.
gunEnd.transform.LookAt (aim);
//get mouse click and asks if we can shoot yet
if (Input.GetKey(KeyCode.Mouse0)&&canShoot) {
StartCoroutine(shoot());
}
}
public IEnumerator shoot(){
//instantiates the bullet
gunEnd.transform.LookAt (aim);
bullet = Instantiate (bulletPrefab, gunEnd.transform.position, Quaternion.identity);
bullet.transform.LookAt (aim);
Rigidbody b = bullet.GetComponent<Rigidbody> ();
b.AddRelativeForce (Vector3.forward*force);
canShoot = false;
yield return new WaitForSeconds (fireRate);
canShoot = true;
}
}
无论位置或鼠标位置如何,这只会向后射击,位于同一位置的播放器后面。
感谢您的阅读,希望对您有所帮助! :)
我认为问题来自此行:
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
因为将“屏幕位置”(Input.mousePosition)转换为世界空间时没有任何“深度”,所以我怀疑Camera.main.ScreenToWorldPoint
返回错误的值,即使您尝试设置aim.z
的值aim.z
几行。
试试这个代替:
mousePos = Input.mousePosition;
mousePos += Camera.main.transform.forward * 10f ; // Make sure to add some "depth" to the screen point
aim = Camera.main.ScreenToWorldPoint (mousePos);
顺便说一句,在上面的代码中,使用了Camera.main
,但是您应该使用在Start函数中初始化的缓存版本: mainCam
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.