Had a fairly simple little script that simply used Input.GetAxis horizontal to move my player object left and right. All was good until I decided I needed to put a limit on the amount of movement along the x axis.
After adjusting my script with some Mathf.Clamp coding I’m getting some weird effects. Basically its rotating my playerObject 180 degrees around the x axis and 180 degrees around the y axis. (affectively turning it upside down and facing rearwards)
public int Min = 30;
public int Max = 30;
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, 0);
GetComponent<Rigidbody>().velocity = movement * speed;
GetComponent<Rigidbody>().position = new Vector3(Mathf.Clamp (GetComponent<Rigidbody>().position.x, Min, Max), 0, transform.position.z);
}
Any ideas/suggestions to as why this is happening? The actual clamping/restriction on the x axis is working fine, but this damn rotation is making my head spin (excuse the pun…lol)
???
First off Clamp
sets the value of a variable between a range, but you are giving a zero range, i.e. min = max = 30
. This could be a problem. Secondly never use GetCompoenent
, or Find
etc. methods in update, they are very resource consuming; set them in start to variable. Thirdly, don’t set the velocity of Rigidbody
it is very easy to mess up there, because it’s the physics engines job. First try to just use AddForce
, or MovePosition
etc. Lastly, what you are doing is that you change the x value of the velocity, and then put the rigid body at new x position, 0, old z position
so you are kind of applying torque, that is why it rotates. I don’t know what you actually are trying to achieve from this code exactly so can’t help you much. If you are trying to limit movement, then first calculate the new movement vector followed by a check to see it fits the criteria, and only then move the rigid body.
P.S. I don’t know if this is your real moment code, if so then you should put it in Update
instead, because it calculations are going to waste every time FixedUpdate
is called and frame isn’t really updated. That’s kinda a lot. I also hope you are using Time.deltaTime
to smooth the movement.