DeveloperBreeze

Unity Player Controller Blueprint

using UnityEngine;

// Basic player controller for Unity
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    [Header("Player Settings")]
    public float moveSpeed = 5f;
    public float jumpHeight = 2f;
    public float gravity = -9.81f;
    public Transform cameraTransform;

    private CharacterController characterController;
    private Vector3 velocity;
    private bool isGrounded;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        MovePlayer();
        RotateCamera();
    }

    void MovePlayer()
    {
        // Check if the player is on the ground
        isGrounded = characterController.isGrounded;
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f; // A small negative value to keep the player grounded
        }

        // Get input for movement
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");

        // Calculate movement direction
        Vector3 move = transform.right * moveX + transform.forward * moveZ;
        characterController.Move(move * moveSpeed * Time.deltaTime);

        // Jumping logic
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        // Apply gravity
        velocity.y += gravity * Time.deltaTime;
        characterController.Move(velocity * Time.deltaTime);
    }

    void RotateCamera()
    {
        // Get input for mouse movement
        float mouseX = Input.GetAxis("Mouse X");
        float mouseY = Input.GetAxis("Mouse Y");

        // Rotate player along the y-axis
        transform.Rotate(Vector3.up * mouseX);

        // Rotate camera along the x-axis
        cameraTransform.Rotate(Vector3.left * mouseY);
    }
}

Features of the Blueprint

  1. Character Controller: This script uses Unity's CharacterController component to handle player movement and collision detection. Make sure to attach this component to your player object.
  2. Movement: The player can move forward, backward, and strafe using the keyboard inputs. The MovePlayer method handles this.
  3. Jumping: Basic jumping mechanics are implemented, allowing the player to jump if they are grounded.
  4. Gravity: Simulated gravity ensures the player falls back to the ground after jumping.
  5. Camera Rotation: Mouse input is used to rotate the player character and camera, providing a first-person or third-person view depending on the setup.

Usage Instructions

  1. Attach Script: Add this script to your player GameObject in Unity.
  2. Configure Components: Ensure that a CharacterController component is also attached to the same GameObject.
  3. Camera Transform: Assign the main camera or a specific camera transform to the cameraTransform field in the Unity Inspector.
  4. Tweak Settings: Adjust moveSpeed, jumpHeight, and gravity values in the Inspector to fit your game's requirements.

Extension Ideas

  • Animation Integration: Add animator components and trigger animations based on movement and jump states.
  • Advanced Physics: Integrate more complex physics interactions, such as slopes or surface friction.
  • Networking: Adapt the controller for multiplayer environments using Unity’s networking solutions.

Related Posts

More content you might like

Tutorial

Avoiding Memory Leaks in C++ Without Smart Pointers

void loadData() {
    char* buffer = new char[1024];
    try {
        if (someCondition()) {
            throw std::runtime_error("Something went wrong");
        }
        // more code...
    } catch (...) {
        delete[] buffer;
        throw;
    }
    delete[] buffer;
}

Not elegant. Easy to forget or misplace deletes. Let's go better.

Apr 11, 2025
Read More
Tutorial

Deep Copy in C++: How to Avoid Shallow Copy Pitfalls

class Deep {
public:
    int* data;

    Deep(int val) {
        data = new int(val);
    }

    // Copy constructor for deep copy
    Deep(const Deep& other) {
        data = new int(*other.data);
    }

    // Assignment operator for deep copy
    Deep& operator=(const Deep& other) {
        if (this != &other) {
            delete data;
            data = new int(*other.data);
        }
        return *this;
    }

    ~Deep() {
        delete data;
    }
};

If your class handles dynamic memory:

Apr 11, 2025
Read More
Tutorial

Implementing a Domain-Specific Language (DSL) with LLVM and C++

Tools & Libraries:

  • C++ Compiler: A modern C++ compiler with C++17 support (e.g., GCC 10+, Clang 12+).
  • CMake: For building and managing your project.
  • LLVM: Version 15+ (or later). Ensure you have the LLVM libraries and headers installed.
  • Optional: Git for version control and sample project management.

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • JavaScript enables features like dropdown menus, modal windows, sliders, and real-time updates.
  • Examples: Search suggestions, form validations, chat applications.
  • Using AJAX or Fetch API, JavaScript retrieves and updates data without reloading the page.
  • Example: Infinite scrolling on social media feeds.

Dec 10, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!