我正在尝试制作一个简单的游戏,当玩家按下鼠标按钮时,立方体会追逐鼠标。
到目前为止,这是我的代码:
public class PlayerCubeController : MonoBehaviour {
public float speed = 1.0f;
Vector3 targetPos = new Vector3();
void Start () {
speed = speed * 0.01f;
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
Debug.Log (Input.mousePosition);
targetPos = Input.mousePosition;
targetPos.z = 0;
} else if (Input.GetMouseButtonUp (0)) {
targetPos = transform.position;
}
transform.position = Vector3.Lerp (transform.position, targetPos, speed * Time.deltaTime);
}
}
不幸的是,立方体永远不会朝向鼠标的方向;我可以将鼠标放在屏幕的左下角,但立方体仍然会显示在右上方。
奇怪的是,如果我将鼠标放在屏幕的左侧,立方体就会直线上升。
谁能告诉我哪里出错了?
答案 0 :(得分:3)
您的问题很简单:Input.mousePosition
在屏幕坐标中定义鼠标位置(例如,从(0,0)到(1920,1080))。如果你想从鼠标位置获得一个3d点,你还有一个额外的步骤。我看到两种可能性:
使用Camera.main.ScreenToWorldPoint
并手动指定相机的距离:
var v = Input.mousePosition;
v.z = 10.0;
v = Camera.main.ScreenToWorldPoint(v);
// Move your cube to v
或者使用光线投射来获取您的观点,例如使用Camera.main.ScreenPointToRay
:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
// Move your cube to hit.point
答案 1 :(得分:2)
简而言之,您需要从屏幕转换为世界坐标。这是一个例子
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
有些事情:
{
// Server authentication info
"servers": [
{
"host": "52.41.186.122",
"username": "ubuntu",
// "password": "ubuntu"
// or pem file (ssh based authentication)
"pem": "aws-key/xanthelabs.pem"
}
],
// Install MongoDB in the server, does not destroy local MongoDB on future setup
"setupMongo": true,
// WARNING: Node.js is required! Only skip if you already have Node.js installed on server.
"setupNode": true,
// WARNING: If nodeVersion omitted will setup 0.10.43 by default. Do not use v, only version number.
"nodeVersion": "4.4.7",
// Install PhantomJS in the server
"setupPhantom": true,
// Show a progress bar during the upload of the bundle to the server.
// Might cause an error in some rare cases if set to true, for instance in Shippable CI
"enableUploadProgressBar": true,
// Application name (No spaces)
"appName": "deep-app",
// Location of app (local directory)
"app": "/home/cortana/Desktop/deep-app",
// Configure environment
"env": {
"PORT": 8888,
"ROOT_URL": "http://52.41.186.122",
"MONGO_URL": "mongodb://localhost/meteor"
},
// Meteor Up checks if the app comes online just after the deployment
// before mup checks that, it will wait for no. of seconds configured below
"deployCheckWaitTime": 15
}