0
\$\begingroup\$
func _physics_process(delta):
    direction = Vector3(0, 0, 0)
        if Input.is_action_pressed("ui_left"):
            direction.x += 1
        if Input.is_action_pressed("ui_right"):
            direction.x -= 1
        if Input.is_action_pressed("ui_up"):
            direction.z += 1
        if Input.is_action_pressed("ui_down"):
            direction.z -= 1
        direction = direction.normalized()
        direction = direction * speed * delta
        if velocity.y > 0:
            gravaty = -20
        else:
            gravaty = -30

        velocity.y += gravaty * delta
        velocity.x = direction.x
        velocity.z = direction.z

        velocity = move_and_slide(velocity, Vector3(0, 1, 0))


        if is_on_floor() and Input.is_key_pressed(KEY_SPACE):
            velocity.y = 10
        var hitCount = get_slide_count()
        if hitCount > 0:
            var collision = get_slide_collision(0)
        if collision.collider is RigidBody:
            collision.collider.apply_impulse(collison.position, -collision.normal)
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Consider what happens in your code when hit_count is 0.

# This line is skipped, so collision is never defined
if hitCount > 0:
    var collision = get_slide_collision(0)

# This still executes, but collision is not defined
if collision.collider is RigidBody:

You should only perform the latter check if hit_count > 0:

if hitCount > 0:
    var collision = get_slide_collision(0)
    if collision.collider is RigidBody:
        collision.collider.apply_impulse(collison.position, -collision.normal)
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .