0

我试图让我的角色通过在它的 y 轴上旋转来面对鼠标。它旋转了一点,但它不面向鼠标。相机的位置在玩家的正上方,在正交视图中我看到了许多其他自上而下的射击游戏示例,几乎和我的一模一样,所以我不知道是什么问题,请帮忙谢谢。

using UnityEngine;
using System.Collections;

public class playermovementscript : MonoBehaviour { 

public float movementspeed = 5f; 
public float bulletspeed  = 10f;
public GameObject bullet; 
public GameObject shooter;  
public Vector3 target;  
public Camera camera;

// Use this for initialization
void Start () {  
    //refrence to main camera
    Camera camera;

}

// Update is called once per frame
void Update () {

    //call movement function in every frame
    movement (); 

    // cheek for input of f in every frame if true execute shoot function
    if (Input.GetKeyDown (KeyCode.F)) {
        shoot();
    } 

 } 




void movement(){

    // makes refrence to gameobjects rigidbody and makes its velocity varible to equal values of axis x and y
    gameObject.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal")*movementspeed,0,Input.GetAxisRaw("Vertical")*movementspeed); 

// makes vector 3 type target equall to mouse position on pixial cordinates converted in to real world coordniates
    target = camera.ViewportToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.transform.position.y - transform.position.y)); 

    //target.x -= transform.position.x; 
    //target.z -= transform.position.z;
    // states the vector 3 values of target 
    Debug.Log (target);  
    // makes object local z face target and iniziates up axis
    transform.LookAt (target,Vector3.up);

}  
4

1 回答 1

1

打算尝试解释发生了什么...

target = camera.ViewportToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.transform.position.y - transform.position.y)); 

上面的代码试图将屏幕空间中的鼠标位置(测量从 (0,0) 到屏幕宽度/高度的位置(以像素为单位))到视口空间(测量相同的屏幕但具有不同的度量,它测量从(0,0)到(1,1)的位置)。

团结一致

如果您仍希望使用“ViewportToWorldPoint”,那么您可以执行“ScreenToViewportPoint”,然后使用“ViewPortToWorldPoint”。

否则,您可以从一开始就考虑使用“ScreenToWorldPoint”。

于 2015-10-10T00:36:14.773 回答