0 votes

Hello,

I'm new to programming and to Godot.
My code for my player is working fine including gravity "velocity.y += GRAVITY"

However for an enemy, gravity is not working the same.
The y values 50 each below is simply for me to understand where is the problem, the enemy simply goes on a straight line when I would like gravity to pull further down.
I'm guessing there is a problem with the line "velocity.y += GRAVITY", I don't know.

Here is the code:

(the commented part probably has no connection, ignore)

extends KinematicBody2D

const GRAVITY = 50
export var jumpheight = -50
export var jump
reach = -150
var velocity = Vector2()

#var jumping_enabled = false

func physicsprocess(delta):
velocity.y = jumpheight
velocity.x = jump
reach
velocity.y += GRAVITY

# if jumpingenabled == true:
*# velocity.y = jump
height

# velocity.x = jump_reach
*# velocity.y += GRAVITY**

velocity = move_and_slide(velocity)

*#func _on_Area2D_body_entered(body):
*# jumping_enabled = true**

Godot version Godot_v3.1.2
in Engine by (12 points)

Gravity is 50 and jump -50 so don't they cancel each other.

Yes you’re right, they cancel each other out.
What I need is to simulate a jump.
I have achieved this (jump) in another scene with jump -750 and gravity 35 (another character).
In this scene, when I change the jump & gravity values I’m getting a linear upwards or downwards depending on jump and gravity values.
Which is why I changed them to equal each other wanting to find out if it’s a problem with “velocity.y += GRAVITY”.
I was assuming “velocity.y += GRAVITY” is different than “velocity.y = jump_height” where the former keeps accumulating gravity value to velocity instead of simply adding, seems they are cancelling each other out.
My idea was player enters area2d and enemy jumps forward.
Any idea what’s missing from the code to be able mimic a jump?
Thanks.

1 Answer

0 votes
var grav = 0
var grav_strength = 1
var jump_height = -10

func _process(delta):
    var vel = Vector2()
    if is_on_floor():
        vel.y = grav_strength
        grav = 0
        #vel.y has to be vel.y > 0 so is_on_floor() can be true
    else:
        grav += grav_strength

    if Input.is_action_pressed("jump") && is_on_floor():
        grav = jump_height
    #jump code has to be after fall code so grav can be overwritten

    vel.y += grav
    move_and_slide(vel,Vector2.UP)
by (256 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.