write all the code necessary to make a 2d plataformer videogame in unity3d
- User
write all the code necessary to make a 2d plataformer videogame in unity3d
Assistant
Here is a basic 2D platformer game in Unity:
// Player controller public class PlayerController : MonoBehaviour { public float speed = 5f; public float jumpSpeed = 8f; public float gravity = 20f; private Rigidbody2D rb; private Animator anim; private bool isGrounded; void Start() { rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); } void Update() { // Get input and move horizontally float xInput = Input.GetAxis("Horizontal"); rb.velocity = new Vector2(xInput * speed, rb.velocity.y); // Flip player sprite based on direction if (xInput > 0) { transform.eulerAngles = new Vector3(0, 0, 0); } else if (xInput < 0) { transform.eulerAngles = new Vector3(0, 180, 0); } // Jump if (Input.GetButtonDown("Jump") && isGrounded) { rb.velocity = new Vector2(rb.velocity.x, jumpSpeed); isGrounded = false; } // Play walking animation anim.SetFloat("Speed", Mathf.Abs(xInput)); } void FixedUpdate() { // Apply gravity rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y - gravity * Time.fixedDeltaTime); } void OnCollisionEnter2D(Collision2D col) { // Set isGrounded to true if player collides with ground layer if (col.gameObject.layer == LayerMask.NameToLayer("Ground")) { isGrounded = true; } } }This script handles:
- Moving the player horizontally with input
- Jumping when the player presses the jump button and is grounded
- Applying gravity
- Flipping the sprite based on direction
- Playing a walking animation
You would also need:
- A tilemap for the level
- Colliders on the ground tiles
- An animator with walking animations
- A sprite for the player
- A camera to follow the player
This covers the basics of a simple 2D platformer in Unity. Let me know if you have any other questions!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.