I'm Making a 2D game, from the top view, I have it so you can walk around and the camera follows (fyi the player is a sphere atm). I want it so that the gun will rotate around the sphere, pointing at wherever the mouse is, I originally tried:
var mouseX;
var mouseY;
function Update () {
mouseX = Input.mousePosition.z;
mouseY = Input.mousePosition.y;
transform.Rotate(Vector3(mouseX,mouseY,0));
}
but that did not work (it spun out of control on all axis, i dont want it to go up and down (y axis) rotate in a circle on the z and x axis). i looked at other posts and found this (it was for a 2D side view)
but i have no idea what that stuff means nor how to use it
if someone could help me get a code and explain how it works, or change one of these it would greatly help
Try this code.
It will determine the World Position where your mouse cursor is at the exact height of your character. The character now always looks at this point which means the character faces your mouse cursor at all times.
//attach this script to your camera and drag your character GameObject in the fpc slot in the inspector
private var worldPos : Vector3;
private var mouseX : int;
private var mouseY : int;
private var cameraDif : int;
var fpc : GameObject;
function Start () {
//determines how far down the ScreenToWorldPoint is from the camera position
//it's calculated [height of camera] - [height of pivot point of character]
//this is to ensure the character only rotates (via LookAt) along rotation.x and doesn't look up or down
cameraDif = camera.transform.position.y - fpc.transform.position.y;
}
function Update () {
mouseX = Input.mousePosition.x;
mouseY = Input.mousePosition.y;
//this takes your current camera and defines the world position where your mouse cursor is at the height of your character -->translates your onscreen position of mouse into world coordinates
worldPos = camera.ScreenToWorldPoint(Vector3(mouseX, mouseY, cameraDif));
fpc.transform.LookAt(worldPos);
}
Omg finally found what i want searchewd months for it but uhm...
how does it work ? what is Fpc and why he is constantly saying there is no camera attached to gameObject but there is ! can someone help me ?
what to do ?
i got a object called Tank>
tank gots a body wheels camera and turret
i want the turret to move what do i have to give the script and what do
i have to give the variable Fpc ?
could someone please help me ?
The answer to your final question: I think there is a slight spacing error in the code on line 8 above, delete the space btwn the colon and Gameobject var fpc : GameObject; so reads var fpc :GameObject; Once space is deleted, save and drag this script onto your camera, now in the inspector you will see a variable labeled fpc , now drag your game object to the right of that variable into the inspector, this will apply the mouse movement to that object.