Godot Version
4.2.2
Question
I have my player and an NPC. I have an NPC that walks back and forth using RayCast2D nodes so that it knows to turn around and move until next colliding object. How I currently have the NPC set up, it works just fine with any collision set up, but I found that if my player touches the NPC from behind it, it marks it as a collision and the NPC turns around rather than just keep going (I know I don’t have this set up so no surprise here).
How is something like this set up where the NPC is still an object the player or NPC can’t walk through, but can’t affect the direction the NPC is going while still keeping the NPC collision with the world objects? I’m assuming part of this is the Layer and Mask settings for Player, NPC, and RayCast2D, but I can’t get it right when switching layers for all 3 nodes (player, world/tile, and NPC).
extends CharacterBody2D
const SPEED = 25.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var direction = 1
@onready var animated_sprite_2d = $AnimatedSprite2D
@onready var ray_cast_left = $RayCastLeft
@onready var ray_cast_right = $RayCastRight
func _physics_process(delta):
# Add the gravity.
velocity.y += gravity * delta
# Flip sprite for right movement
if direction > 0:
animated_sprite_2d.flip_h = true
elif direction < 0:
animated_sprite_2d.flip_h = false
if ray_cast_right.is_colliding():
direction = -1
animated_sprite_2d.flip_h = true
animated_sprite_2d.play("Hop")
if ray_cast_left.is_colliding():
direction = 1
animated_sprite_2d.flip_h = false
animated_sprite_2d.play("Hop")
#Set horizontal movement
velocity.x = -SPEED
position.x += direction * SPEED * delta
RayCast2D for right and left currently have Collison Mask 1
Player is on Layer 1 and Mask 2
Tiles are Collision Layer 1 and 2 with Collision Mask on 1