A little help with this idea

Godot Version

Godot 4


I’m trying to incorporate bounce physics with a 2d grid based player.

I want the player to bounce continuously and jump higher still when action pressed which I’ve got working but when trying to add a grid based movement on the X angle it all goes wrong.

extends CharacterBody2D

var SPEED = 10
var JUMP_VELOCITY = -260
const BOUNCE = -20
var gravity = 980

var tilesize = 64
var last_pos = Vector2()
var target_pos = Vector2()
var movedir = Vector2()

func _ready():
position = position.snapped(Vector2(tilesize, tilesize))
last_pos = position
target_pos = position


func _process(delta):


  position += SPEED * movedir * gravity * delta
  if position.direction_to(last_pos) >= tilesize - SPEED * delta:
        position = target_pos
  # IDLE
  if position == target_pos:
        last_pos = position
        target_pos += movedir * tilesize

func _physics_process(delta):

  # Add the gravity.


  if not is_on_floor():
        velocity.y += gravity * delta
  elif  is_on_floor():
        velocity.y += BOUNCE * gravity * delta

  if Input.is_action_pressed("ui_accept") and is_on_floor():
        velocity.y += JUMP_VELOCITY + BOUNCE * delta

func get_movedir():
var LEFT = Input.is_action_pressed(“ui_left”)
var RIGHT = Input.is_action_pressed(“ui_right”)

  movedir.x = - int(LEFT) + int(RIGHT)
  if movedir.x !=0 && movedir.y !=0:
        movedir = Vector2.ZERO

Any help in the right direction would be appreciated.

1 Like

You are using move_and_slide and setting position directly, you should only use the former. movedir seems to never take the Y axis into account, you can use

movedir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")

to get movedir, instead of piece by piece like you are.

  if movedir.x !=0 && movedir.y !=0:
        movedir = Vector2.ZERO

These lines reset movedir to zero if both directions are pressed. This seems strange, wouldn’t you not need this if statement at all? I think this is your main issue?

The stray move_and_slide() inside of func get_movedir() is wrong, it should be at the end of _physics_process.

To paste code click the </> button on a new line and paste like so

type or paste code here

Thanks for reply, I’ll keep trying to get it to work with your suggestions.