Hi. I am fairly new to using Unity for 2D games. I am currently making a platformer and when the player is moving the sprite will occasionally “shake like crazy”. This is the script I’m using in Fixed Update.
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
float xSpeed = Input.GetAxis("Horizontal") * 2.0f;
anim.SetFloat("Speed", Mathf.Abs(xSpeed));
this.rigidbody2D.AddForce(new Vector2(xSpeed * MoveFactor, 0f));
// If the input is moving the player right and the player is facing left...
if (h > 0 && !facingRight)
// ... flip the player.
Flip();
// Otherwise if the input is moving the player left and the player is facing right...
else if (h < 0 && facingRight)
// ... flip the player.
Flip();
}
Do you think you could help me fix it?
Try this character controller script:
using UnityEngine;
using System.Collections;
public class PlayerControllerScript : MonoBehaviour {
public float maxSpeed = 3;
bool facingRight;
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
if (move > 0 && !facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip();
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}