How do i have the player move a block in a top down 2d game?

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

What is the best way of achieving this? My block is a RigidBody2d. I imagine id need to use body_entered to check for collisions and add_force to move it but I’m too newb to know how to code it and the docs don’t have code use examples to get me started. Any one achieve this if so how?

What node are you using for your player?

tam0705 | 2018-12-12 03:23

KinematicBody2d

sumguy05 | 2018-12-12 03:45

You need to specify how the player wants to move the box, i.e. if the player pushes the box diagonally, will there be a specific angle that the box will move in, or does the angle depend on which direction the player is pushing the box from?

shield | 2018-12-12 06:40

:bust_in_silhouette: Reply From: tam0705

I’ll explain to you an example as what I’ll do in Godot 3.0.x

So I bet you have known and used the function move_and_collide(rel vec). That function returns a KinematicCollision2D which is enough to do what you want. KinematicCollision2D has members named collider, which is the object you’re collided with, and normal, which points from collision’s surface to us. You can use collider to check whether you’re touhing with the block or not, and apply the inversed normal to the movable block. Here is it looks like in code:

func _physics_process(delta):
    var collision = move_and_collide(direction * VELOCITY * delta)
    if collision.collider.is_in_group("movable blocks"):
        var speed_of_moving_object = collision.collider.normal * -1
        speed_of_moving_object *= BLOCK_SPEED
        collision.collider.move_and_collide(speed_of_moving_object * delta)

I’ll leave the rest (for example blocks can only be moved in 4way direction) to you :slight_smile:

I haven’t known or used any function as I haven’t a fucking clue what I’m doing lol. Would this code go in my player or my block? If it’s my block should it be a KinematicBody2d instead of a RigidBody2d?

sumguy05 | 2018-12-12 12:48