How do I limit my top-down movement?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Adele

I need to limit my character’s movement to a certain area, bu couldn’t find anything that will help. I’m using characterbody2d and this script for movement:
extends CharacterBody2D

@export var speed = 300

func get_input():
var input_direction = Input.get_vector(“left”, “right”, “up”, “down”)
velocity = input_direction * speed

func _physics_process(delta):
get_input()
move_and_slide()

Maybe you could add walls, floors, or ceilings that trap you character inside the desired area?

godot_dev_ | 2023-04-20 16:47

:bust_in_silhouette: Reply From: ChrissWalters

Please be more specific, why and how the movement should be restricted.

This will lock a player in the game window. It’s in C#, but you can easily change it to gd script, the functions are nearly named the same:

public override void _PhysicsProcess(double delta)
{
    var InputVector = new Vector2(
        Input.GetActionStrength("MoveRight") - Input.GetActionStrength("MoveLeft"),
        Input.GetActionStrength("MoveDown") - Input.GetActionStrength("MoveUp")
    ).Normalized();       

    if (InputVector != Vector2.Zero)
    {
        Velocity = InputVector * SPEED;
        MoveAndSlide();
    }
    else //InputVector == 0
    {
        // Reduce velocity gradually until it comes to a complete stop
        Velocity = Velocity.MoveToward(Vector2.Zero, FRICTION);
        MoveAndSlide();
    }

    //Boundries:

    float Radius = GetNode<CollisionShape2D>("CollisionShape2D").Shape.GetRect().Size.X /2;
    var ScreenSize = GetViewportRect().Size;
    Vector2 NewPosition = new Vector2();

    if(Position.X + Radius >= ScreenSize.X || Position.X - Radius <= 0 || Position.Y + Radius >= ScreenSize.Y|| Position.Y - Radius <= 0)
    {
        NewPosition.X = Mathf.Clamp(Position.X, 0 + Radius, ScreenSize.X - Radius);
        NewPosition.Y = Mathf.Clamp(Position.Y, 0 + Radius, ScreenSize.Y - Radius); 
        Position = NewPosition;
    }        
}

Thank you! I will try it out

Adele | 2023-04-21 05:02