0% found this document useful (0 votes)
2 views

ExUnityMoveCodeC#

The document contains a Unity C# script for player movement in a 2D game, allowing for horizontal movement and jumping. It utilizes Rigidbody2D for physics, Animator for animations, and checks for ground contact to manage jumping. Key features include adjustable speed and jump force, as well as sprite flipping based on movement direction.

Uploaded by

Victor Afonso
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ExUnityMoveCodeC#

The document contains a Unity C# script for player movement in a 2D game, allowing for horizontal movement and jumping. It utilizes Rigidbody2D for physics, Animator for animations, and checks for ground contact to manage jumping. Key features include adjustable speed and jump force, as well as sprite flipping based on movement direction.

Uploaded by

Victor Afonso
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System.

Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using Unity.Burst.CompilerServices;
using UnityEngine;

public class PlayerMove : MonoBehaviour


{
public float speed;
public float jumpForce;
private bool isJumping;
private float move;
[SerializeField] private LayerMask layerGround;

Rigidbody2D rb;
Animator anim;
SpriteRenderer spR;
BoxCollider2D bxC2D;

void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
spR = GetComponent<SpriteRenderer>();
bxC2D = GetComponent<BoxCollider2D>();
}

// Update is called once per frame


void Update()
{
Move();
Jump();
}
void Move()
{
move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(move * speed, rb.velocity.y);
if(move > 0)
{
anim.SetBool("Run", true);
spR.flipX = false;
}
if(move < 0)
{
anim.SetBool("Run", true);
spR.flipX = true;
}
if(move == 0)
{
anim.SetBool("Run", false);
}
}

void Jump()
{
if(Input.GetButton("Jump"))
{
if(!isJumping)
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
if(rb.velocity.y > jumpForce)
{
rb.velocity = rb.velocity.normalized * jumpForce;
}
if(isGrounded())
{
isJumping = false;
}
else
{
isJumping = true;
}

}
private bool isGrounded()
{
RaycastHit2D ground = Physics2D.BoxCast(bxC2D.bounds.center,
bxC2D.bounds.size, 0, Vector2.down, 0.1f, layerGround);
return ground.collider !=null;
}
}

You might also like