- Home /
Moving Object At MousePosition.X
Hello
i'm Trying to Make a CrossHair But Not As Texture, i'm Making it as Gameobject
but i got problem in making it follow the mouse
public GameObject CrossHair;
//Start Void
CrossHair = Instantiate(CrossHair,transform.position,transform.rotation) as GameObject;
//Update Void
CrossHair.transform.position.x =(Camera.main.ScreenToWorldPoint(Input.mousePosition).x);
what is the wrong in this code
Answer by robertbu · Apr 26, 2013 at 07:37 PM
Does this code compile? The big issues is that ScreenToWorldPoint() takes a Z parameter that is the distance into the scene to place the object. I'll assume you don't want the Z value to change for your crosshair object. This assumes you are looking down the Z axis. This can be written more compactly (less steps), but for the sake of understanding:
Vector3 v3Pos = Input.mousePosition;
// Set 'Z' to the distance in front of the camera;
v3Pos.z = Mathf.Abs(CrossHair.transform.position.z - Camera.main.transform.position.z);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
v3Pos.y = CrossHair.transform.position.y;
CrossHair.transform.position = v3Pos;
Thank You, but it didnt work
maybe because my Game TopDown not FPS?
so i dont need to move CrossHair Up And Down , it should be at the player height
i guess we shouldn't use Camera in this situation
some times the code show this error
transform.position assign attempt for 'CrossHair(Clone)' is not valid. Input position is { -Infinity, 2.000000, Infinity }.
UnityEngine.Transform:set_position(Vector3)
Crosshair:Update() (at Assets/Scripts/$$anonymous$$ultiPlayer/Crosshair.cs:35)
Your answer
Follow this Question
Related Questions
Gun object following mouse. 2 Answers
Draw crosshair INSTEAD of cursor. 1 Answer
Camera rotation around player while following. 6 Answers