To create a 2D platformer game in Unity3D, you'll need multiple scripts to handle different aspects of the game. Here's an example of the code you could use:
- PlayerController.cs:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
private bool isJumping = false;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
float movement = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(movement * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && !isJumping)
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
isJumping = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isJumping = false;
}
}
}
- CameraFollow.cs:
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
private void LateUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
}
}
- Collectible.cs:
using UnityEngine;
public class Collectible : MonoBehaviour
{
public int scoreValue = 1;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
GameManager.instance.AddScore(scoreValue);
Destroy(gameObject);
}
}
}
- GameManager.cs:
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public Text scoreText;
private int currentScore = 0;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
public void AddScore(int value)
{
currentScore += value;
scoreText.text = "Score: " + currentScore;
}
}
Remember to attach these scripts to the appropriate GameObjects in your scene, set up the input axes and tags in Unity, and create the necessary UI elements for the game.