- Home /
Question by
gamingtuber081 · May 15 at 03:33 PM ·
2dmovementgamepad
When gamepad is connected, character plays walking animation,When gamepad connected, character walks on it's own
When gamepad is connected, my character plays walking animation. When jumping, it moves to the left a bit, even thought it's not supposed to.
The problem doesn't exist when gamepad isn't connected, because then character stays in place until i press assigned key.
===
Here's my PlayerMovement script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;
public LayerMask jumpableGround;
private float dirX = 0f;
public float moveSpeed = 7f;
public float jumpForce = 14f;
// 0 1 2 3
private enum MovementState { idle, running, jumping, falling }
public AudioSource jumpSFX;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpSFX.Play();
}
UpdateAnimationState();
if (Input.GetButtonDown("X"))
{
SceneManager.LoadScene("Level 16");
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ice"))
{
moveSpeed = 9.5f;
}
if (collision.gameObject.CompareTag("StickyPlatform"))
{
moveSpeed = 3f;
}
if (collision.gameObject.CompareTag("Terrain"))
{
moveSpeed = 7f;
}
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
if (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}
anim.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}
Comment