Character Movement in Unity…
2 min readDec 29, 2022

Codes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb2D;
private float moveSpeed;
private float jumpForce;
private bool isJumping;
private float moveHorizontal;
private float moveVertical;
// Start is called before the first frame update
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
moveSpeed = 3f;
jumpForce = 60f;
isJumping = false;
}
// Update is called once per frame
void Update()
{
moveHorizontal = Input.GetAxisRaw("Horizontal");
moveVertical = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
{
rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
}
if (!isJumping && moveVertical > 0.1f )
{
rb2D.AddForce(new Vector2(0f, moveVertical * jumpForce), ForceMode2D.Impulse);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Platform")
{
isJumping = false;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Platform")
{
isJumping = true;
}
}
}
From the program:
void Update()
{
moveHorizontal = Input.GetAxisRaw("Horizontal");
moveVertical = Input.GetAxisRaw("Vertical");
}
- moveHorizontal and moveVertical is a variable that is used to take Horizontal and Vertical Input from the user with up(w), down(s) & left() & right keys using - Input.GetAxisRaw(“Horizontal”);
if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
{
rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
}
if (!isJumping && moveVertical > 0.1f )
{
rb2D.AddForce(new Vector2(0f, moveVertical * jumpForce), ForceMode2D.Impulse);
}
- moveHorizontal > 0.1f means user is clicking right arrow or d key same as for moveHorizontal < -0.1f means user is clicking left arrow or a key…
rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed, 0f), ForceMode2D.Impulse);
- AddForce will add force on rb2D and new Vector2(moveHorizontal * moveSpeed, 0f) will move the the object Horizontally according to the moveSpeed in X-axis and cuz of 0f, the gameObject will not move in Y-axis…and same mechanism is for isJumping…
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Platform")
{
isJumping = false;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Platform")
{
isJumping = true;
}
}
- If the gameObject touches the object having tag “Platform” then isJumping becomes false…It is OnTriggerEnter…
- And same for OnTriggerExit, isJumping becomes true…
That’s all…Thank you for reading😉:)
click here to follow me in LinkedIn for more updates…
click here to follow me in GitHub for more updates…