我试图通过在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);
}
答案 0 :(得分: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)的位置。
在Unity中
如果您仍想使用“ViewportToWorldPoint”,那么您可以执行“ScreenToViewportPoint”,然后使用“ViewPortToWorldPoint”进行操作。
否则,您可以从一开始就考虑使用“ScreenToWorldPoint”。