problem with scripting movement
Hey, so I've followed a guide by code monkey where he shows how to script jumping and movement. All the jumping part is ok (although I had to change it a little to work, I don't know why) but there is a problem with moving, it doesn't do that at all. using System; using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Payer : MonoBehaviour {
Rigidbody2D rigid2d;
public Func<BoxCollider2D> bCollider2D;
float jumpVelocity = 50f;
public BoxCollider2D bCollider2d;
public RaycastHit2D raycastHit2d;
public LayerMask platformsLayerMask;
float moveSpeed = 40f;
public void Start()
{
rigid2d = transform.GetComponent<Rigidbody2D>();
bCollider2D = transform.GetComponent<BoxCollider2D>;
}
private void Update()
{
if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
{
rigid2d.velocity = Vector2.up * jumpVelocity;
}
}
private bool isGrounded()
{
RaycastHit2D raycastHit2d = Physics2D.BoxCast(bCollider2d.bounds.center, bCollider2d.bounds.size, 0f, Vector2.down, .1f, platformsLayerMask);
Debug.Log(raycastHit2d.collider);
return raycastHit2d.collider != null;
}
private void HandleMovement()
{
if (Input.GetKeyDown(KeyCode.A))
{
rigid2d.velocity = new Vector2(-moveSpeed, rigid2d.velocity.y);
} else
{
if (Input.GetKeyDown(KeyCode.D))
{
rigid2d.velocity = new Vector2(+moveSpeed, rigid2d.velocity.y);
} else
{//no keys pressed
rigid2d.velocity = new Vector2(0, rigid2d.velocity.y);
}
}
}
}
Does anybody know what to do?
here is a link to yt channel if necessary, about 9:30 minute.
Edit: I forgot to add. Yes, my player is called Payer. I just thought it would be funny
Answer by DonJorris · Aug 01, 2021 at 09:24 AM
You need to call the HandleMovement() method inside the Update () function. Otherwise the movement code is never called.
Your answer
![](https://koobas.hobune.stream/wayback/20220613041030im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to determine if an Enemy is moving left or right? 2 Answers
so how to i create a moving barrel 0 Answers
Face direction of a Vector 3 1 Answer
Character movement 0 Answers
Implementing a "flyer" game in with the old CardBoard Google sdk 2 Answers