- Home /
Character object inexplicably jumps up on the Y axis when arrow keys are pressed to move it along x or z
Hello,
I'm hoping somebody can shed light on this Unity problem I have. I'm very new to all of this (both Unity and programming beyond goto print), so I apologise in advance if this is really obvious and I've just missed it after several hours of trying random fixes and glaring at my monitor.
I have a character object (a parent composed of three child objects) which is controlled along the preset Horizontal and Vertical axes. I cobbled together a script which appeared to make the character happily move along the floor in any direction and stop almost as soon as the player stops pressing any of the four arrow keys (as required). However, when any of the arrow keys are pressed, the object jumps from y=2.5 to y=4.38 and hovers in the air from then on. I tried setting the Freeze Y Position constraint on the object; this stopped the object from ending up in the air, but slowed movement down greatly and prevented any movement at all when pressing the up or right arrow keys.
I have no idea what's causing this; I've included my movement script below for reference. If anyone can shed light on this, I'd be very grateful.
{
public float speed;
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
if (Input.GetAxis("Horizontal")!=0)
{
rigidbody.AddForce (movement * speed * Time.deltaTime);
}
else if (Input.GetAxis("Vertical")!=0)
{
rigidbody.AddForce (movement * speed * Time.deltaTime);
}
else
{
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
rigidbody.Sleep ();
}
}
}
EDIT: So... I was looking further into this; turns out that if you check the Convex setting on the Mesh Collider of a Plane, it causes all kinds of funky behaviour (as your character object effectively tries to move along an invisible curvature of your game scene). I thought I could leave this here for fellow noobs who might have stumbled into the same issue, but I'm happy to delete it if requested.
might be the Vecotr3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
This might need to be something like:
Vecotr3 movement = new Vector3(moveHorizontal, transform.position.y, moveVertical);
cos it might have a strange position for y, and is using that ins$$anonymous$$d of what you think....
hope that is a) correct and b) makes sense
Thanks, $$anonymous$$larax - the edit I wrote above seems to have done the job, but I'll definitely take a look at this.
Thank you L$$anonymous$$itch123 That was my problem I must have clicked it without knowing
I can go to sleep now ;) Thanks for posting