A
A
AntiLockYT2020-05-06 11:02:56
Unity
AntiLockYT, 2020-05-06 11:02:56

Why is the character not walking?

I can't walk, what's the problem?

Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MobileCont : MonoBehaviour
{
  
  public float horizontalSpeed;
  float speedX;
  Rigidbody2D rb;
  bool isGrounded;
  public Transform groundCheck;
  public float jumpForce;
  public float checkRadius;
  public LayerMask whatIsGround;
  
  
  private int extraJumps;
  public int extraJumpsValue;
  
    void Start()
    {
    extraJumps = extraJumpsValue;
        rb = GetComponent<Rigidbody2D>();
    }
  
    void FixedUpdate()
    {
    
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
    
    if(Input.GetKeyDown(KeyCode.Escape))
    {
         Application.Quit();
    }
    if (Input.GetKey(KeyCode.A))
    {
      speedX = -horizontalSpeed;
    }
    else if (Input.GetKey(KeyCode.D))
    {
      speedX = horizontalSpeed;
    }
     
}

void OnTriggerEnter2D(Collider2D other)
     {
       if (other.tag == "KillPL")
       {
         SceneManager.LoadScene(0);
       }
     }


  void Update()
  {
    if (isGrounded == true)
    {
      extraJumps = extraJumpsValue;
    }
    
    if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
    {
      rb.velocity = Vector2.up * jumpForce;
    extraJumps--;
    }
    else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
    {
      rb.velocity = Vector2.up * jumpForce;
    }
  }
  
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kot Kotov, 2020-05-07
@kot123123

Hello, I don't want to upset you, but your character does not have movement set, here, put this in void update or FixedUpdate

rb.velocity = new Vector2(horizontalSpeed,rb.velocity.y);

and you can combine the code from update and fixedupdate , so it will be easier.
You can also simplify checking the floor under your feet:
void OnCollisionEnter2D(Collision2D coll) 
{
       if(coll.gameObject.tag == "Ground")
       {
                isGrounded = true;
       }
}

This is suitable for basic checking of the floor underfoot (platformer or runner).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question