Position changing though set position code running
I always want to set my main play at -2.5f unit in y direction. When I drag character then it change its position slightly and this is some what frustrating to me.
I have written following code :
void Update ()
{
if (Input.GetMouseButton (0)) {
Vector3 worldPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
worldPos.x = Mathf.Clamp(worldPos.x,-2.5f,2.5f);
worldPos.y = -2.5f;
worldPos.z = 0f;
Debug.Log("world pos : " + worldPos);
transform.position = Vector3.Slerp(transform.position,worldPos,Time.deltaTime * speed);
}
}
Following 2 images give you more idea about my problem.
You can clearly seen above image that value is gone above -2.5f. But I am directly setting value on update.
Even -2.5f is displayed in console.
Please give me some help in this. I want to stick my player on y position always.
Answer by corewise · Jan 18, 2016 at 05:17 PM
I'm not 100% sure, but I think you should use Vector3.Lerp and not Vector3.Slerp. You could also add a Rigidbody and freeze its Y-position.
EDIT: Vector3.Lerp interpolates between two points whereas Vector3.Slerp interpolates between two directions and magnitudes.
Yes, you are right Vector3.Lerp solved the problem. I am on 2d game so no freeze position and rotation exist.
please post your reply as answer.