We will have 3 scenes. The first one is a plain Node called 'World.tscn'. The second is a KinematicBody2d ('Player') and third is a StaticBody2d ('Enemy')
Underneath both the 'Player' and 'Enemy' we have a Sprite, and CollsionShape2D. The Sprite for both is the Godot icon, however for the 'Enemy' one, we set the modulate property to red. The collision shape is a rectangle matching the extents of Sprite.
For the 'Player', we have four RayCast2D nodes as children. They are named Left, Right, Down, and Up. We have to check the Enable in the Inspector and change cast to, for Left, Right, and Up. For Down, the default value is ok. For Up, set it to (0,-50). For Right, set it to (50,0), and Left to (-50,0). We should be able to see the arrows pointing in correct direction. We should enable visibility on only 1 of the nodes at a time so we can see the individual rays pointing in the correct direction.
Finally to the 'World', we attach this script:
extends Node
const SPEED = 100.0
onready var Player = preload("res://Player.tscn")
onready var Enemy = preload("res://Enemy.tscn")
var player
var enemy
func _ready():
setup()
func _process(delta):
var motion = Vector2(0.0, 0.0)
if Input.is_action_pressed("ui_right"):
motion.x = SPEED
elif Input.is_action_pressed("ui_left"):
motion.x = -SPEED
elif Input.is_action_pressed("ui_down"):
motion.y = SPEED
elif Input.is_action_pressed("ui_up"):
motion.y = -SPEED
player.move_and_slide(motion)
var left = player.get_node("Left")
var right = player.get_node("Right")
var up = player.get_node("Up")
var down = player.get_node("Down")
if left.is_colliding():
print("left")
elif right.is_colliding():
print("right")
elif up.is_colliding():
print("up")
elif down.is_colliding():
print("down")
else:
print("Not colliding")
func setup():
player = Player.instance()
add_child(player)
player.position = Vector2(100.0, 100.0)
enemy = Enemy.instance()
enemy.position = Vector2(200.0, 200.0)
add_child(enemy)
If we are to left of the 'Enemy' and such that the ray intersects (that is close enough), the Right ray will collide. We set the window as (300,300) in Project Settings. This shows the output including the text:
No comments:
Post a Comment