- Home /
Need help understanding ScreentoWorldPoint
I'm trying to get my player character to always face the mouse wherever it may be while on screen. I figured I could get the ScreentoWorldPoint back from the mouse position and then just have the sprite rotate towards the point whenever updating the frame but it's throwing back errors, including a type where a variable,value, or method group are expected, Invalid arguments in the ScreenToWorldPoint method, and not being able to convert and object to a vector3.
Now from my understanding, Input.mousePositionx, Input.mousePosition.y, and 0f are all floats which should work in ScreenToWorldPoint, right? I'm not seeing where I'm going wrong here.
Here's the code:
using UnityEngine;
using System.Collections;
public class PlayerControls : MonoBehaviour {
Vector3 worldPos;
float x;
float y;
float speed = 5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
worldPos = Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x,Input.mousePosition.y, 0.0f));
x = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
y = Input.GetAxis("Vertical") * speed * Time.deltaTime;
transform.Translate(x, y, 0);
transform.LookAt(worldPos);
}
}
Answer by robertbu · Dec 18, 2013 at 04:38 AM
There are two problems here. The first one is that you need a 'new' in front of your Vector3() in C#. The second is that the 'z' parameter must be the distance in front of the camera. In perspective mode at least, passing 0 will cause ScreenToWorldPoint() to always return the position of the camera. So the call will look something like:
worldPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, 10.0f));
Note the measurement for the 'z' parameter is from camera plane to the playing surface plane. It is not the distance between the camera and the object. If the camera is aligned with the axes, then the distance is easy to calculate. If the camera is at an angle (i.e. not axes aligned), then ScreenToWorldPoint() is not the way to go.
Correction/Addition: Passing '0' will work fine to find the world x,y values if the camera is Orthographic. The 'z' will be the 'z' position of the camera.
Wow, thanks for the quick reply! I'll make sure to make those changes. Now, I don't quite fully understand memory management for games, but will having the new modifier cause any problems because it is constantly being called and allocating new space for the same Vector3, or is that negligible?
Thanks again for all the help!
wow, super ... i love this forum, it is something like page full of $$anonymous$$i-tutorials. With this i finali can make top-down controled spacecraft