How to create a script that will move a object with the mouse(in the x and y axis only) and have my player model head look at it?
I am a newbie so I have NO idea how I should do it, I have searched online but nothing worked. I know that I need to get the mouse position and then have the object be moved to that position continuously and that the player head should have a ray looking at the object but I have no idea how to script that.
Answer by JedBeryll · Jan 23, 2016 at 08:01 PM
You can start here: http://docs.unity3d.com/Manual/CameraRays.html
Raycasthit can give you all the information you need. The collider that was hit, the world position of the hit etc.
You can write a script that causes an object to follow the hit position like this:
public class MyClass : Monobehaviour {
Transform anObject; //assign this in inspector or by scripting
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // camera.main is the camera tagged as MainCamera so you should only have one of those
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) { //raycast is true if it hits something
anObject.position = hit.point;
}
}
}
As for moving the head I guess you would have to use an animator component but i can't help you with that as i haven't used one yet. Note that i didn't write this in editor so there may be errors in this code.