Hi.
I’m working on a 3rd person game and trying to make the player look at the object the cursor points at.
what i try to do is sending a raycast from cursor, hitting the object, then calculating the direction from player to hit.point and rotating there.
#pragma strict
private var _mousePos :Vector3;
private var _myTransform :Transform;
var mouseMovementFactor :float=1;
function Start () {
_myTransform = transform;
}
function Update () {
_mousePos = Input.mousePosition;
// print(_mousePos);
var myScreenPos:Vector3 = Camera.main.WorldToScreenPoint(_myTransform.position);
// print(myScreenPos);
var dir2Cursor:Vector3 = _mousePos-myScreenPos;
//print(dir2Cursor);
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit:RaycastHit;
var direction:Vector3;
var rotation:Quaternion;
if(Physics.Raycast (ray,hit,10000) && hit.collider.tag!="Player")
{
direction = (hit.point - _myTransform.position);
print("hitting "+hit.collider + " direction from player: "+direction);
}
rotation = Quaternion.LookRotation(direction);
the part of rotating to look at the direction causes me problems.
as for now - the line print("hitting "+hit.collider + " direction from player: "+direction);
prints exactly the object i’m touching.
what i tried so far was
rotation = Quaternion.LookRotation(direction);
_myTransform.rotation = Quaternion.Slerp(_myTransform.rotation,rotation,Time.deltaTime*mouseMovementFactor);
player rotates rightwards only and would only slow down if i take cursor left.
_myTransform.rotation.y = Quaternion.Slerp(_myTransform.rotation,rotation,Time.deltaTime*mouseMovementFactor).y;
_myTransform.rotation.z = Quaternion.Slerp(_myTransform.rotation,rotation,Time.deltaTime*mouseMovementFactor).z;
(x makes it flip on its back)
makes it to slerp to a specific rotation and not move from there.
_myTransform.LookAt(hit.point);
makes it completely go crazy.
var newDir = Vector3.RotateTowards(_myTransform.forward, direction, mouseMovementFactor*Time.deltaTime, 0.0);
_myTransform.rotation.y = Quaternion.LookRotation(newDir).y;
_myTransform.rotation.z = Quaternion.LookRotation(newDir).z;
y - barely moves it
z makes it go strange irrelevent directions
please help?