0% found this document useful (0 votes)
51 views3 pages

Unity Player Movement Script Guide

This C# script controls player movement in a Unity game. It gets input from the player, checks if the player is grounded, and applies forces to the player's rigidbody to move and jump. It handles movement on the ground differently than in air, applying drag when grounded and limiting speed. It also includes a cooldown for jumping to prevent continuous jumping.

Uploaded by

ttfhghbhbn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views3 pages

Unity Player Movement Script Guide

This C# script controls player movement in a Unity game. It gets input from the player, checks if the player is grounded, and applies forces to the player's rigidbody to move and jump. It handles movement on the ground differently than in air, applying drag when grounded and limiting speed. It also includes a cooldown for jumping to prevent continuous jumping.

Uploaded by

ttfhghbhbn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

using System.

Collections;
using [Link];
using UnityEngine;
using TMPro;

public class PlayerMovementTutorial : MonoBehaviour


{
[Header("Movement")]
public float moveSpeed;

public float groundDrag;

public float jumpForce;


public float jumpCooldown;
public float airMultiplier;
bool readyToJump;

[HideInInspector] public float walkSpeed;


[HideInInspector] public float sprintSpeed;

[Header("Keybinds")]
public KeyCode jumpKey = [Link];

[Header("Ground Check")]
public float playerHeight;
public LayerMask whatIsGround;
bool grounded;

public Transform orientation;

float horizontalInput;
float verticalInput;

Vector3 moveDirection;

Rigidbody rb;

private void Start()


{
rb = GetComponent<Rigidbody>();
[Link] = true;

readyToJump = true;
}

private void Update()


{
// ground check
grounded = [Link]([Link], [Link], playerHeight *
0.5f + 0.3f, whatIsGround);

MyInput();
SpeedControl();

// handle drag
if (grounded)
[Link] = groundDrag;
else
[Link] = 0;
}

private void FixedUpdate()


{
MovePlayer();
}

private void MyInput()


{
horizontalInput = [Link]("Horizontal");
verticalInput = [Link]("Vertical");

// when to jump
if([Link](jumpKey) && readyToJump && grounded)
{
readyToJump = false;

Jump();

Invoke(nameof(ResetJump), jumpCooldown);
}
}

private void MovePlayer()


{
// calculate movement direction
moveDirection = [Link] * verticalInput + [Link] *
horizontalInput;

// on ground
if(grounded)
[Link]([Link] * moveSpeed * 10f,
[Link]);

// in air
else if(!grounded)
[Link]([Link] * moveSpeed * 10f * airMultiplier,
[Link]);
}

private void SpeedControl()


{
Vector3 flatVel = new Vector3([Link].x, 0f, [Link].z);

// limit velocity if needed


if([Link] > moveSpeed)
{
Vector3 limitedVel = [Link] * moveSpeed;
[Link] = new Vector3(limitedVel.x, [Link].y, limitedVel.z);
}
}

private void Jump()


{
// reset y velocity
[Link] = new Vector3([Link].x, 0f, [Link].z);

[Link]([Link] * jumpForce, [Link]);


}
private void ResetJump()
{
readyToJump = true;
}
}

Common questions

Powered by AI

The PlayerMovementTutorial script separates handling of vertical and horizontal inputs through the MyInput() method, which assigns values from Input.GetAxisRaw("Horizontal") and Input.GetAxisRaw("Vertical") to horizontalInput and verticalInput variables, respectively. These inputs are then combined with the player's orientation to compute a movement direction vector within the MovePlayer() method. Horizontal inputs affect movement along the player's sideways axis (left-right), while vertical inputs affect forward-backward motion, both adjusted relative to the orientation component of the player. This setup enables dynamic and responsive movement by factoring in camera or model rotation directly into navigation adjustments .

In the PlayerMovementTutorial script, the orientation Transform is used to determine the player's forward and right vectors, which are essential for calculating the movement direction. By utilizing the orientation.forward and orientation.right vectors, the script adapts the player's movement relative to their current facing direction, rather than a fixed world direction. This allows for a more intuitive and flexible control scheme where, for example, pressing forward always moves the player in the current direction of the viewing or controlling camera .

In the PlayerMovementTutorial script, the jump key serves as the input trigger for initiating the jump functionality. This key is defined by the public variable 'jumpKey', which is defaulted to KeyCode.Space. This allows users to trigger a jump when this specific key is pressed, assuming other conditions (such as readiness to jump and being grounded) are met. The key can be modified easily by changing the value assigned to 'jumpKey', allowing for customizable keybindings and catering to user preferences or accessibility needs, thus enhancing the flexibility and usability of the control scheme .

Using a Rigidbody in the PlayerMovementTutorial script allows for comprehensive physics interactions, providing a natural and dynamic response to forces, collisions, and simulated physics events. The Rigidbody component efficiently emulates real-world physics, such as gravity influence and inertia, essential for realistic player motion. This setup affects gameplay by offering a tangible sense of weight and motion, where player actions such as jumping or collision responses align with expected physical properties. Employing a Rigidbody enhances immersion by ensuring player control and environmental interactions are grounded in realistic simulations, crucial for engaging and intuitive gameplay experiences .

The PlayerMovementTutorial script differentiates between ground and air movement using a ground check that updates the 'grounded' boolean. When the player is grounded, movement forces are applied directly based on the moveSpeed, which is adjusted by physics drag parameters to control speed. In contrast, when the player is not grounded, an airMultiplier is applied to the moveSpeed to accommodate the different dynamics required for air movement. This allows for reduced control when the player is airborne, simulating realistic physics where the player cannot change direction as easily as when on solid ground .

The PlayerMovementTutorial script handles collisions with specific layers using a ground check that involves raycasting to detect whether the player is contacting a particular layer, as specified by the 'whatIsGround' LayerMask. This allows the script to determine if the player is currently grounded, an essential factor for enabling jumping and applying correct drag forces. By detecting only designated ground layers, the script ensures accurate gameplay mechanics where the player can rely on environmental surfaces for movement dynamics, crucial for maintaining consistent game logic and preventing exploits or unrealistic behavior when interacting with uncontrolled or unintended layers .

Velocity magnitude control in the PlayerMovementTutorial script is implemented through the SpeedControl() method. Here, the code calculates a flat velocity vector (ignoring the Y component) to assess the player's horizontal speed. If this speed surpasses the defined moveSpeed, the script normalizes this vector and scales it back to moveSpeed, maintaining the current direction but reducing the magnitude. This regulation ensures that player movement adheres to set speed constraints, preventing unintended physics exploits or gameplay imbalances due to excessive speed, which could occur from strong forces applied during movement .

The airMultiplier in the PlayerMovementTutorial script influences how movement forces are applied when the player is airborne. When the player is not grounded, the airMultiplier scales the moveSpeed, effectively decreasing the force applied to movement inputs compared to when the player is grounded. This simulates reduced control while airborne, as the airMultiplier typically has a value less than one, ensuring airborne motion respects realistic physics constraints and mimics the limited influence a player has over their trajectory when not in contact with a surface .

The PlayerMovementTutorial script manages the player's jump functionality through a combination of boolean checks and timed resets. The readiness to jump is controlled by the boolean variable 'readyToJump', which initially is set to true in the Start() method. When the player presses the designated jump key (KeyCode.Space by default) and the player is ready to jump and grounded, the script sets 'readyToJump' to false and calls the Jump() method. This prevents multiple jumps from occurring within a short time frame. A jump force is then applied to the player's Rigidbody. Following the jump, the method Invoke() is used to call ResetJump() after a specified jump cooldown, resetting 'readyToJump' to true, allowing for another jump only after the cooldown period .

The PlayerMovementTutorial script integrates drag effects by conditionally altering the Rigidbody's drag property based on whether the player is currently grounded. Drag is set to a value specified by 'groundDrag' when grounded, moderating the velocity to simulate friction against the ground. When airborne, drag is set to zero, allowing for freer movement as there is no surface-induced resistance. This approach realistically simulates how friction affects movement, with increased resistance when the player is in contact with a surface and less when in the air, influencing how the player accelerates and decelerates under different conditions .

You might also like