unity3d中2d自上而下射击游戏的旋转控制出现问题
本文关键字:控制 问题 旋转 2d 自上而下 射击游戏 unity3d | 更新日期: 2023-09-27 18:17:04
我试图让我的角色面对鼠标在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);
}
我要试着解释一下发生了什么…
target = camera.ViewportToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.transform.position.y - transform.position.y));
以上代码试图将屏幕空间中的鼠标位置(以像素为单位测量从(0,0)到屏幕宽度/高度的位置)转换为Viewport空间(测量相同的屏幕,但使用不同的测量方法,它测量从(0,0)到(1,1)的位置)。
在统一- 屏幕空间测量:原点(0,0)到最大宽度/高度
- 视口测量:原点(0,0)到(1,1)
- 参考:http://docs.unity3d.com/ScriptReference/Camera.html
如果你希望仍然使用"ViewportToWorldPoint",那么你可以做一个"ScreenToViewportPoint",然后跟着一个"ViewportToWorldPoint"。
否则,你可以考虑从一开始就使用"ScreenToWorldPoint"