I’m currently trying to create a 2D platformer game as a first project, but I’m having some trouble with the animating. I have a sprite created, and I have the actual animation; when I press Play on the Unity console, the player starts the running animation, and I can move around just fine. However, I would like to set it up so that on start, the player doesn’t move, and will only animate when walking left or right. I will include my script so far, but if anyone needs to know any other information, feel free to ask. I will willingly provide screenshots, data, files, etc. to help.
using UnityEngine;
using System.Collections;
public class NewMovement : MonoBehaviour {
public Rigidbody2D rb;
public float moveSpeed;
public float jumpPower;
private bool faceLeft = false;
private bool moving = false;
void Start () {
gameObject.GetComponent<Rigidbody2D> ();
faceLeft = false;
//I'm fairly certain that a bunch of the code has to be put in Start, so info is retrieved from the get-go.
}
void Movement()
{
Vector2 v = GetComponent<Rigidbody2D>().velocity;
if (Input.GetKey ("d"))
{
v.x = moveSpeed;
GetComponent<Rigidbody2D>().velocity = v;
moving = true;
}
//Boolean values should be based off of the keys D and A; the sprite should only animate when one of those keys are pressed.
else if (Input.GetKey ("a"))
{
v.x = moveSpeed * -1.0f;
GetComponent<Rigidbody2D>().velocity = v;
moving = true;
}
else {
v.x = 0.0f;
GetComponent<Rigidbody2D>().velocity = v;
}
if (gameObject.transform.position.y <= -4.5) {
if (Input.GetKeyDown ("w")) {
v.y = jumpPower;
GetComponent<Rigidbody2D> ().velocity = v;
}
}
}
void SpriteFlip ()
{
Vector2 face = GetComponent<Transform>().transform.localScale;
if (Input.GetKeyDown ("a")) {
if (!faceLeft){
face.x *= -1;
faceLeft = true;
GetComponent<Transform>().transform.localScale = face;
}
}
if (Input.GetKeyDown ("d")) {
if (faceLeft){
face.x *= -1;
faceLeft = false;
GetComponent<Transform>().transform.localScale = face;
}
}
}
void Animate()
{
//This is where the code will go for the animating, I hope.
}
void Update ()
{
Movement ();
SpriteFlip ();
Animate ();
}
}