- Home /
Gun Look at mouse script not working
I want my gun to look at my mouse like in this game:
http://www.youtube.com/watch?v=rAwIzZ49V7M
Here is my script:
Vector3 gunLookPos = new Vector3(0f, Input.mousePosition.y, Input.mousePosition.x);
Camera.main.ScreenToWorldPoint(gunLookPos);
myTransform.LookAt(gunLookPos);
Do you have your X and Z values reversed in gunLookPos? Are you assigning your Camera.main... return value to something?
Answer by robertbu · Aug 25, 2013 at 12:58 AM
ScreenToWorldPoint() takes a Vector representing 'x', 'y' and 'z'. 'x', and 'y' come from the mouse, 'z' is the distance from a plane going through the camera to the plane the character is on. The code below calculates that distance dynamically, but for a 2D game, with the camera a fixed distance from the 2D surface, you can hard code that value. This code assumes the camera is looking towards positive 'z' like the default setup you get when you create a new scene:
Vector3 gunLookPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, myTransform.position.z - Camera.main.transfrom.position.z);
gunLookPos = Camera.main.ScreenToWorldPoint(gunLookPos);
myTransform.LookAt(gunLookPos, Vector3.forward);
$$anonymous$$y game is actually looking down the x - axis, just so that I can make my player move down his forward position. I tried this code:
Vector3 gunLookPos = new Vector3(Input.mousePosition.x, myTransform.position.y - Camera.main.transform.position.y, Input.mousePosition.y);
gunLookPos = Camera.main.ScreenToWorldPoint(gunLookPos);
myTransform.LookAt(gunLookPos, Vector3.forward);
and this one:
Vector3 gunLookPos = new Vector3(myTransform.position.x - Camera.main.transform.position.x, Input.mousePosition.x, Input.mousePosition.y);
gunLookPos = Camera.main.ScreenToWorldPoint(gunLookPos);
myTransform.LookAt(gunLookPos, Vector3.forward);
But they dont seem to work. Am I missing something?
Can someone please help me? I really need help. I still cannot figure this out! I have tried everything. If you want, I will send you a build of the game or something.
If you are looking down the 'x', then you calculate the distance for the 'z' parameter of he Vector3 as:
myTransform.position.x - Camera.main.transfrom.position.x
I think the problem is that you were switching around the input.mousPosition. Also, robertbu is correct. It should work if you use that combined with his original answer. Good luck!
It works actually, thanks. Yes $$anonymous$$rProfessorTroll, that was the problem. Thanks robertbu
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to check for a mouse drag 0 Answers
Distribute terrain in zones 3 Answers