Hi all, I am doing a 2d platform game and I am needing help with this topic. I have a character with rigibody2d and I wanted to move up my character by any staircase. I don’t know how I have to do this.
I have three rigidbody2d, I did to walk, jump, run and all colliders for this level. But when I want to move up the stairs, I don’t know how to do. I have added a gameobject with a collider for each stairs, and these were added in other layer to identify the object.
Also, I have created new animations for my character to change the sprites. But it is not working correctly.
this is the code:
using UnityEngine;
using System.Collections;
public class ErikAnimatorScript : MonoBehaviour {
private Animator anim;
private bool facingRight = true;
private bool grounded = true;
private float groundRadius = 0.2f;
private bool allowedUp = false;
private bool movingUp = false;
private bool allowedDown = false;
private bool movingDown = false;
public float maxSpeed = 10f;
public Transform groundCheck;
public LayerMask whatIsGround;
public float jumpForce = 700f;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void FixedUpdate () {
float moveX = Input.GetAxis ("Horizontal");
float moveY = Input.GetAxis("Vertical");
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
anim.SetBool ("Ground", grounded);
anim.SetFloat ("Speed", Mathf.Abs (moveX));
anim.SetFloat ("vSpeed", Mathf.Abs (moveY));
rigidbody2D.velocity = new Vector2 (moveX * maxSpeed, rigidbody2D.velocity.y);
if (moveX > 0 && !facingRight) {
Flip ();
} else if (moveX < 0 && facingRight) {
Flip ();
}
if (movingUp) {
rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x, moveY * (maxSpeed / 2));
}
}
void Update() {
if (grounded && Input.GetKeyDown (KeyCode.Space)) {
anim.SetBool("Ground", false);
rigidbody2D.AddForce(new Vector2(0, jumpForce));
}
if (allowedUp && Input.GetKeyDown (KeyCode.W)) {
movingUp = true;
anim.SetBool("Up", false);
anim.SetBool("MovingUp", true);
rigidbody2D.gravityScale = 0f;
}
}
void Flip() {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Staircases") {
allowedUp = true;
anim.SetBool("Up", true);
}
}
void OnTriggerStay2D(Collider2D other) {
}
void OnTriggerExit2D(Collider2D other) {
allowedUp = false;
movingUp = false;
anim.SetBool("Up", false);
rigidbody2D.gravityScale = 2.5f;
}
}