I’m creating a 2D game using Unity. I’ve created a set of animations using a single sprite texture split into multiple sprites and then keyframed using unity’s animation editor.
These animations are also controlled by an animation controller attached to the main sprite. In the animator the transition between animations follows the 2D example provided by unity. When the player idle the idle animation will play, when the speed is greater than 0.1 then the running animation will play. Back to idle if less than 0.1.
The script attached to the player sprite is the same player controller from the 2D example without the jump stuff added:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
[HideInInspector]
public bool facingRight =true;
//TODO Add variables for jumping
public float moveForce = 365f; // Amount of force added to move the player left and right.
public float maxSpeed = 5f;
private Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
// TODO Ground checks and Jumping.
}
void FixedUpdate()
{
// Cache the horizontal input.
float h = Input.GetAxis("Horizontal");
// The Speed animator parameter is set to the absolute value of the horizontal input.
anim.SetFloat("Speed", Mathf.Abs(h));
// If the player is changing direction (h has a different sign to velocity.x) or hasn't reached maxSpeed yet...
if(h * rigidbody2D.velocity.x < maxSpeed)
// ... add a force to the player.
rigidbody2D.AddForce(Vector2.right * h * moveForce);
// If the player's horizontal velocity is greater than the maxSpeed...
if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
// ... set the player's velocity to the maxSpeed in the x axis.
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
// 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();
}
void Flip ()
{
// Switch the way the player is labelled as facing.
facingRight = !facingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Also attached to the sprite is a rigidbody2D and a 2DBox collider.
When I click play to test this however I get the same error: index < m_IntCount over and over. The player sprites behaviour is as follows: he will begin the float upwards slowly, you can sill move him left and right but the run animation will not play.
Where am I going wrong?