Unity3d,在鼠标位置拍摄

时间:2017-07-18 06:43:46

标签: c# unity3d

我正在创建一个简单的街机游戏但是我在拍摄时遇到了麻烦。玩家将拥有此视图。 enter image description here 我希望玩家从玩家角色上的炮塔射击鼠标位置。

这是我的代码。

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;
    }
}

这只会向后射击,在同一位置的玩家后面,无论位置或鼠标位置如何。

感谢您的阅读,希望您能提供帮助! :)

1 个答案:

答案 0 :(得分:0)

我认为问题来自这一行:

mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

因为“屏幕位置”(Input.mousePosition)在将其转换为世界空间时没有任何“深度”,我怀疑Camera.main.ScreenToWorldPoint返回错误的值,即使您尝试设置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