DeveloperBreeze

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.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Avoiding Memory Leaks in C++ Without Smart Pointers

What’s wrong? If someCondition() returns true, buffer is never deallocated.

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;
}

Apr 11, 2025
Read More
Tutorial

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

  • What shallow vs deep copy means
  • The problems caused by shallow copy
  • How to implement deep copy correctly
  • A practical class example with dynamic memory
  • When to use Rule of Three vs Rule of Five

A shallow copy copies the values of member variables as-is. If your class has a pointer member, both the original and copy point to the same memory.

Apr 11, 2025
Read More
Tutorial

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

#ifndef DSL_LEXER_H
#define DSL_LEXER_H

#include <string>
#include <vector>

enum class TokenType {
    Number,
    Plus,
    Minus,
    Asterisk,
    Slash,
    LParen,
    RParen,
    EndOfFile,
    Invalid
};

struct Token {
    TokenType type;
    std::string text;
    double value; // Only valid for Number tokens.
};

class Lexer {
public:
    Lexer(const std::string& input);
    Token getNextToken();

private:
    const std::string input;
    size_t pos = 0;
    char currentChar();

    void advance();
    void skipWhitespace();
    Token number();
};

#endif // DSL_LEXER_H

Implementation: Lexer.cpp

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

JavaScript isn't limited to the browser anymore. It's being used in diverse domains:

  • Tools like React Native enable building native apps using JavaScript.
  • Example: Facebook's mobile app.

Dec 10, 2024
Read More
Tutorial
python

Build a Multiplayer Game with Python and WebSockets

class TicTacToe:
    def __init__(self):
        self.board = [" "] * 9
        self.current_turn = "X"

    def make_move(self, position):
        if self.board[position] == " ":
            self.board[position] = self.current_turn
            if self.check_winner():
                return f"{self.current_turn} wins!"
            self.current_turn = "O" if self.current_turn == "X" else "X"
            return "Next turn"
        return "Invalid move"

    def check_winner(self):
        win_conditions = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ]
        for condition in win_conditions:
            if self.board[condition[0]] == self.board[condition[1]] == self.board[condition[2]] != " ":
                return True
        return False

We’ll use the websockets library to handle communication between players.

Dec 10, 2024
Read More
Tutorial
csharp

Developing a Real-Time Multiplayer Game with Unity and C#

     using UnityEngine;
     using Unity.Netcode;

     public class PlayerController : NetworkBehaviour
     {
         public float moveSpeed = 5f;
         public float rotateSpeed = 200f;

         void Update()
         {
             if (!IsOwner) return; // Only allow control by the local player

             float move = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
             float rotate = Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime;

             transform.Translate(0, 0, move);
             transform.Rotate(0, rotate, 0);
         }
     }

This script allows the player to move forward and backward using the Vertical axis and rotate using the Horizontal axis. The IsOwner check ensures that only the player who owns the object can control it.

Aug 14, 2024
Read More
Code
csharp

Unity Inventory System using Scriptable Objects

No preview available for this content.

Aug 12, 2024
Read More
Code
csharp

Calculate Sum of Numbers in Array

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!