Im making a adventure game and I want to have the player's life decrease when it touches a monster.

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

I asked a similar question earlier but the code did not work.

This is the script for the player so far:

extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

func get_input():
velocity = Vector2()
if Input.is_action_pressed(‘ui_right’):
velocity.x += 1
if Input.is_action_pressed(‘ui_left’):
velocity.x -= 1
if Input.is_action_pressed(‘ui_down’):
velocity.y += 1
if Input.is_action_pressed(‘ui_up’):
velocity.y -= 1
velocity = velocity.normalized() * speed

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

:bust_in_silhouette: Reply From: JohnPrattAllen

THIS ONLY PRINTS WHAT OBJECT YOU COLLIDED WITH BUT ITS CLOSER TO THE RESULT THAN THE ABOVE CODE

extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

func get_input():
velocity = Vector2()
if Input.is_action_pressed(‘ui_right’):
velocity.x += 1
if Input.is_action_pressed(‘ui_left’):
velocity.x -= 1
if Input.is_action_pressed(‘ui_down’):
velocity.y += 1
if Input.is_action_pressed(‘ui_up’):
velocity.y -= 1
velocity = velocity.normalized() * speed

func _physics_process(delta):

get_input()
velocity = move_and_slide(velocity)

var collision = move_and_collide(velocity * delta)
if collision:
	print("I collided with ", collision.collider.name)

note: im working on finding out how to make the life and damage next, Any more help would be nice.

JohnPrattAllen | 2020-06-07 08:51

That’s about it


if collision:
    if collision.collider == monster(or whatever name you given to the monster scene):
        health -= 10(assuming you already have a variable for health)

if health <= 0:
    die()

and you don’t have to use move_and_slide and move_and_collide at the same time.so, delete that move_and_slide.

M15F17 | 2020-06-07 19:06

thanks, looks good.

JohnPrattAllen | 2020-06-08 02:35