using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PlayerController : MonoBehaviour { public Rigidbody rig; public float moveSpeed; public int score; public float jumpForce; private bool isGrounded; void Update() { float x = Input.GetAxisRaw("Horizontal") * moveSpeed; float z = Input.GetAxisRaw("Vertical") * moveSpeed; rig.velocity = new Vector3(x, rig.velocity.y, z); Vector3 vel = rig.velocity; vel.y = 0; if (vel.x != 0 || vel.z != 0) { transform.forward = vel; } if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true) { isGrounded = false; rig.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); } if (transform.position.y < -5) { GetComponent<PlayerController>().GameOver(); } } void OnCollisionEnter(Collision collision) { if (collision.GetContact(0).normal == Vector3.up) { isGrounded = true; } } public void GameOver() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } public void AddScore(int amount) { score += amount; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter