gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
write me a script with C# for moving and jumping in my new 2d game
- User
write me a script with C# for moving and jumping in my new 2d game
- Assistant
Sure, here's a simple example script for moving and jumping in a 2D game using C# scripting language.
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public float speed = 10f; // speed of movement public float jumpForce = 500f; // force of jump private bool isGrounded = false; // check if player is grounded public Transform groundCheck; // check if player is grounded float groundRadius = 0.2f; public LayerMask whatIsGround; //check what layer is ground private Rigidbody2D rb2d; void Start() { rb2d = GetComponent<Rigidbody2D>(); //get rigid body component } void FixedUpdate() { isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround); float moveHorizontal = Input.GetAxis("Horizontal"); //get horizontal axis input rb2d.velocity = new Vector2(moveHorizontal * speed, rb2d.velocity.y); //flip player sprite when moving left if (moveHorizontal < 0) { transform.localScale = new Vector2(-1, 1); } //flip player sprite when moving right if (moveHorizontal > 0) { transform.localScale = new Vector2(1, 1); } //jump when space bar is pressed and player is on ground if (Input.GetKeyDown(KeyCode.Space) && isGrounded) { rb2d.AddForce(new Vector2(0, jumpForce)); } } }