UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Make me a Walking/Running system with instructions on how to set up and use"
/* Make sure to have a Character Controller component attached to your player object in the Unity scene */ using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController controller; public float walkSpeed = 2f; public float runSpeed = 6f; public float gravity = -9.81f; private Vector3 velocity; // Start is called before the first frame update void Start() { controller = GetComponent<CharacterController>(); } // Update is called once per frame void Update() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 move = transform.right * horizontal + transform.forward * vertical; // Check if the player is running or walking if (Input.GetKey(KeyCode.LeftShift)) { controller.Move(move * runSpeed * Time.deltaTime); } else { controller.Move(move * walkSpeed * Time.deltaTime); } // Apply gravity if (controller.isGrounded && velocity.y < 0) { velocity.y = -2f; } velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } } /* Instructions to set up and use in Unity: 1. Create a new 3D GameObject (e.g., a Capsule) to represent the player. 2. Add a Character Controller component to the player GameObject. 3. Create a new script in your Assets folder and name it "PlayerMovement". 4. Copy the code above into the PlayerMovement script and save it. 5. Attach the PlayerMovement script to the player GameObject. 6. Adjust the walkSpeed, runSpeed, and gravity values in the script as needed. 7. Press Play in Unity and use the WASD keys to move the player and Left Shift to toggle between walking and running. */