This is a 2D platformer developed in Unity, and it is programmed using C#.
Here’s a simple example of 2D Platformer script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platformer_Script : MonoBehaviour
{
private Rigidbody2D rb;
//private Animator animator;
[Header("Prameters:")]
public float speed = 5f;
public float scale = 1.5f;
public float jumpForce = 5f;
public float lifes = 0f;
[Header("Ground Check:")]
public bool isGrounded = false;
public bool DrawGroundCheck = true;
public float GroundCheckRadius = 0.1f; // Radius to check for the ground
public LayerMask GroundLayer; // Layer mask for the ground
public Transform GroundCheckPosition;
[Header("Head Check:")]
public bool isHeaded = false;
public bool DrawHeadCheck = true;
public float HeadCheckRadius = 0.1f; // Radius to check for the ground
public LayerMask HeadLayer; // Layer mask for the ground
public Transform HeadCheckPosition;
private float horizontalInput;
void Start()
{
transform.localScale = new Vector3(scale, scale, scale);
//animator = GetComponent();
rb = GetComponent();
}
void Update()
{
// Get horizontal input from keyboard or virtual controller
horizontalInput = 0f;
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
horizontalInput = 1f;
}
else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
horizontalInput = -1f;
}
// Set running animation
//animator.SetBool("isRunning", horizontalInput != 0);
// Handle flipping the player
if (horizontalInput != 0)
{
transform.localScale = new Vector3(Mathf.Sign(horizontalInput) * scale, scale, scale);
}
// Handle jumping
if ((Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.UpArrow)))
{
Jump();
}
// Check if grounded
Collider2D groundDetected = Physics2D.OverlapCircle(GroundCheckPosition.position, GroundCheckRadius, GroundLayer);
isGrounded = groundDetected != null;
Collider2D headDetected = Physics2D.OverlapCircle(HeadCheckPosition.position, HeadCheckRadius, HeadLayer);
if (headDetected != null && !isHeaded)
{
isHeaded = true;
}
if (isGrounded)
{
isHeaded = false;
}
// Set jumping animation
//animator.SetBool("isJump", !isGrounded);
}
void FixedUpdate()
{
// Apply movement using Rigidbody2D
rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);
}
public void Jump()
{
if (isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
void OnDrawGizmosSelected()
{
// Visualize the detection radius in the Scene view
if (DrawGroundCheck)
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(GroundCheckPosition.position, GroundCheckRadius);
}
if (DrawHeadCheck)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(HeadCheckPosition.position, HeadCheckRadius);
}
}
}
For more information, please refer to the documentation. Click Here
© S.Verse. All Rights Reserved. Written by Soubhik Mukherjee