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

#include "ScopedPointer.h"

void loadData() {
    ScopedArray<char> buffer(new char[1024]);

    if (someCondition()) {
        return; // no memory leak!
    }

    // buffer is auto-deleted when going out of scope
}

Some legacy APIs require raw pointers. You can still use get():

Apr 11, 2025
Read More
Tutorial

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

This causes both a.data and b.data to point to the same memory. When both destructors run, delete is called twice on the same pointer — undefined behavior!

A deep copy duplicates the actual data pointed to, not just the pointer.

Apr 11, 2025
Read More
Tutorial

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

#include "DSL/AST.h"
#include <llvm/IR/Constants.h>
#include <llvm/IR/LLVMContext.h>

llvm::Value* NumberExprAST::codegen(llvm::IRBuilder<>& builder) {
    return llvm::ConstantFP::get(builder.getDoubleTy()->getContext(), llvm::APFloat(value));
}

llvm::Value* BinaryExprAST::codegen(llvm::IRBuilder<>& builder) {
    llvm::Value* L = lhs->codegen(builder);
    llvm::Value* R = rhs->codegen(builder);
    if (!L || !R) return nullptr;

    switch (op) {
        case TokenType::Plus:
            return builder.CreateFAdd(L, R, "addtmp");
        case TokenType::Minus:
            return builder.CreateFSub(L, R, "subtmp");
        case TokenType::Asterisk:
            return builder.CreateFMul(L, R, "multmp");
        case TokenType::Slash:
            return builder.CreateFDiv(L, R, "divtmp");
        default:
            return nullptr;
    }
}

Note: We use LLVM’s IRBuilder to simplify the creation of IR instructions. Adjust the code if your LLVM API has evolved by 2025.

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

JavaScript is the engine behind the dynamic behavior of modern websites. It works alongside HTML (structure) and CSS (style) to create a complete web experience.

  • JavaScript enables features like dropdown menus, modal windows, sliders, and real-time updates.
  • Examples: Search suggestions, form validations, chat applications.

Dec 10, 2024
Read More

Discussion 0

Please sign in to join the discussion.

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