Navigation2d use with move_and_slide in Godot - godot

Rewritten and Edited for clarity. Assume that I have a 2d platformer like the following example:
https://github.com/godotengine/godot-demo-projects/blob/master/2d/kinematic_character/player.gd
Now... Say I have the player location (vector2) and the enemy location (vector2). The enemy movement works just like the player in the above example. I use get_simple_path to build an array of pre-existing points that lead from the enemy location to the player location. How do I use that array with move_and_slide to get the enemy from point A to point B?

You could try the following:
const GRAVITY = 1000
const SLOPE_SLIDE_STOP = false
var speed = 250
var velocity = Vector2()
var points = [Vector2(100, 200), Vector2(200, 400), Vector2(400, 800)]
var current_point = null
func _physics_process(delta):
if points and current_point is null:
current_point = points.pop_front()
if current_point:
if current_point.distance_to(position) > 0:
target_direction = (position - current_point).normalized()
velocity.y += delta * GRAVITY
velocity = lerp(velocity, target_speed, 0.1)
velocity = move_and_slide(velocity, target_direction, SLOPE_SLIDE_STOP)
else:
current_point = null

Related

Godot apply_central_force direction is changing after the rigidbody2d is rotated

Simple top down mini golf game. I'm using a rigidbody2d as a ball, and a ray that points from the ball to the mouse. I use apply_central_force towards the mouse position (normalized) * speed. you can see this works fine at first. the ball goes in the direction of the ray. once it gets rotated it doesn't.
Gif of the issue
I tried changing the rigidbody mode to character but it sticks to the wall to much. I tried having a position node be the beginning of the ray and setting its rotation to 0 every frame but that didnt work either. Here is my scene tree and code. all code is in the "Planet" which is the rigidbody ball.
Scene Tree
extends RigidBody2D
const max_length = 2000
onready var beam = $Beam
onready var end = $end
onready var ray = $RayCast2D
onready var begin = $begin
onready var my_line = $Line2D
export var shot_speed = 10
export var default_speed = 10
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_HIDDEN)
shot_speed = default_speed
func _physics_process(delta):
_handle_ray()
func _handle_ray():
var mouse_pos = get_local_mouse_position()
var max_cast_to = mouse_pos.normalized() * max_length
ray.cast_to = max_cast_to
if ray.is_colliding():
end.global_position = ray.get_collision_point()
else:
end.global_position = ray.cast_to
beam.rotation = ray.cast_to.angle()
beam.region_rect.end.x = end.position.length()
if Input.is_action_pressed("Fire"):
shot_speed += 10
if Input.is_action_just_released("Fire"):
apply_central_impulse(ray.cast_to.normalized() * shot_speed)
shot_speed = default_speed

enemy follow player my "player" when it enters the "enemy" detection zone the enemy continues forward (to the left)

what is happening is that my "enemy" is not following the "player", when my player enters the detection area the "enemy" continues straight ahead (to the left).
thank you, if you understand something or need more information let me know
detection zone
enemy code
enemy code:
const EnemyDeathEffect = preload("res://Bots/EnemyDeathEffect.tscn")
export var MAX_SPEED = 60
export var ACCELERATION= 25
export var FRICTION = 700
enum {
IDLE,
WANDER,
CHASE
}
var velocity = Vector2.ZERO
var knockback = Vector2.ZERO
var state = CHASE
var path: PoolVector2Array
onready var sprite = $AnimatedSprite
onready var stats = $Stats
onready var playerDetectionZone = $PlayerDetectionZone
func _physics_process(delta):
knockback = knockback.move_toward(Vector2.ZERO, FRICTION * delta)
knockback = move_and_slide(knockback)
match state:
IDLE:
velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)
seek_player()
WANDER:
pass
CHASE:
var player = playerDetectionZone.player
if player != null:
var direction = (player.position - global_position).normalized()
velocity = velocity.move_toward(direction * MAX_SPEED , ACCELERATION * delta)
print(direction)
else:
state = IDLE
sprite.flip_h = velocity.x > 0
velocity = move_and_slide(velocity)
func seek_player():
if playerDetectionZone.can_see_player():
state = CHASE
func _on_Hurtbox_area_entered(area):
stats.health -= area.damage
knockback = area.knockback_vector * 100
func _on_Stats_no_health():
queue_free()
var enemyDeathEffect = EnemyDeathEffect.instance()
get_parent().add_child(enemyDeathEffect)
enemyDeathEffect.global_position = global_position
I only possible culprit I see is this line:
var direction = (player.position - global_position).normalized()
Here player.position is in its parent local coordinates, while global_position as the name says is in global coordinates. You want this instead:
var direction = (player.global_position - global_position).normalized()
I see this is the way you have on the linked image.
Or if you prefer:
var direction = global_position.direction_to(player.global_position)
Aside from that, it could be that it is changing direction too slowly. Which - given the code - is the same as saying that the ACCELERATION is low, but that is for you to tweak.
I guess it is worth debugging that playerDetectionZone is getting the player, and the CHASE is working correctly.
Common approaches include using a breakpoint, or print. You already have a print for direction. Try also printing player to check the enemy is chasing what you expect it to chase.
For this particular case I also suggest to go to the run the project from the editor, and then go to the Scene panel on the Remote tab, and select the enemy. That would allow you to the properties of the enemy on real time on the Inspector. You should see the state change to CHASE (which would have the value 2), and velocity should also steadily change.
Enabling "Visible Collision Shapes" form the debug menu may also help debugging.
If it is not working, double check the playerDetectionZone has monitoring enabled. Also check that the collision_mask of the playerDetectionZone and the collision_layer of the player are correct.

Kinematic Body 2D not moving

I'm trying to game a game using the Godot Engine but I'm stuck at the beginning! I can't make my KinematicBody2D move!
This is my Player.GD script
extends KinematicBody2D
var velocity = Vector2.ZERO
var move_speed = 480
var gravity = 1200
var jump_force = -720
var right = Input.is_action_pressed("move_right")
var left = Input.is_action_pressed("move_left")
var jump = Input.is_action_pressed("jump")
func _ready():
pass
func _physics_process(_delta):
var move_direction = int(right) - int(left)
velocity.x = move_speed * move_direction
move_and_collide(velocity)
Can someone, please, help me?
All this code will run when the KinematicBody2D is initialized:
var velocity = Vector2.ZERO
var move_speed = 480
var gravity = 1200
var jump_force = -720
var right = Input.is_action_pressed("move_right")
var left = Input.is_action_pressed("move_left")
var jump = Input.is_action_pressed("jump")
In consequence, it will not be taking input in real time. Instead you want the last three lines here:
func _physics_process(_delta):
var right = Input.is_action_pressed("move_right")
var left = Input.is_action_pressed("move_left")
var jump = Input.is_action_pressed("jump")
# …
Those are boolean, by the way. You can get a float from 0.0 to 1.0 if you use Input.get_action_strength instead. Which will also let your code ready for analog input.
I also want to point out that move_and_collide does not take a velocity, but a displacement vector. So to call it correctly, you want to multiply the velocity by delta:
func _physics_process(delta):
# …
move_and_collide(velocity * delta)
Or use move_and_slide, which does take a velocity. By the way, the up parameter that move_and_slide takes is to discern between floor, ceiling, and walls. Without, everything is considered a wall.

my get_viewport().get_mouse_position() isn't working right godot GDscript

I'm trying to make a 2d platformer where you spawn an object and try to jump on it in the air before it falls.
the problem is when I try to spawn the tile it doesn't spawn where Is the cursor at
it adds a relative value to the position that I don't know how to get rid of it.
you see when I try to instance a scene it takes the cursor position and viewport value into account but then something happens and I fount the object spawning way too far.
see where is the cursor at and where did the tile spawn
, same thing here
, and here
-here is how I'm grouping the nodes and scenes-
and this is the script I'm using, it's in the player1 scene
extends KinematicBody2D
#
var score : int = 0
export var speed : int = 200
export var jumpforce : int = 600
export var gravity : int = 800
onready var AB1 = preload("res://player1AB.tscn")
var vel :Vector2 = Vector2()
onready var sprite : Sprite = get_node("sprite_idile")
onready var ui : Node = get_node("/root/mainscene1/CanvasLayer/ui")
onready var audioplayer : Node = get_node("/root/mainscene1/Camera2D/audio_player")
func _physics_process(delta):
vel.x = 0
# movement inputs
if Input.is_action_pressed("move_left"):
vel.x -= speed
if Input.is_action_pressed("move_right"):
vel.x += speed
# applying the velcoty
vel = move_and_slide(vel,Vector2.UP)
#apllying gravty
vel.y += gravity * delta
#jump input
if Input.is_action_just_pressed("jump") and is_on_floor():
vel.y -= jumpforce
# where the sprite facing
if vel.x < 0:
sprite.flip_h = true
if vel.x > 0:
sprite.flip_h = false
if Input.is_action_just_pressed("restart"):
death()
func death ():
get_tree().reload_current_scene()
func collect_coin (value):
score += value
ui.set_score_text(score)
audioplayer.play_coin_sfx()
func _input(event):
if event.is_action_pressed("click"):
var ABT1 = AB1.instance()
add_child(ABT1)
var XN = null
XN = get_viewport().get_mouse_position()
ABT1.position = XN
important stuff
onready var AB1 = preload("res://player1AB.tscn")
func _input(event):
if event.is_action_pressed("click"):
var ABT1 = AB1.instance()
add_child(ABT1)
var XN = null
XN = get_viewport().get_mouse_position()
ABT1.position = XN
this the same problem in Godot form check it out if possible in case someone answered there
https://godotforums.org/discussion/27007/my-get-viewport-get-mouse-position-isnt-working-right#latest
If you don't have an extra Viewport
My first intuition is to get get_global_mouse_position and set global_position. That way you don't have to deal with any relative positioning:
ABT1.global_position = get_global_mouse_position()
Alternatively, you can check if the event is InputEventMouse, make it local with make_input_local, and get InputEventMouse.position from it:
func _input(event):
if event is InputEventMouse and event.is_action_pressed("click"):
var ABT1 = AB1.instance()
add_child(ABT1)
event = make_input_local(event)
ABT1.position = event.position
This approach would make it easier to then add touch support, because it does not rely on any function that gives you the mouse position. See my answer for Holding screen touch in godot.
If you have an extra Viewport
First of all, make sure you put your Viewport inside a ViewportContainer (otherwise it does not get input, see _input not called for a node inside a Viewport). Then we can use that ViewportContainer to get our coordinates.
Something like this:
func _input(event):
if event is InputEventMouse and event.is_action_pressed("click"):
var ABT1 = AB1.instance()
add_child(ABT1)
var container = find_parent("ViewportContainer") as ViewportContainer
if container != null:
event = container.make_input_local(event)
event = make_input_local(event)
ABT1.position = event.position
Notice there I'm using the function find_parent. It matches by name of the Node, not by type. Another approach you can try is using get_viewport().get_parent().
And yes, that should work regardless of stretch mode.

How To Make KinematicBody2D Move By Drag in One Direction in GDScript?

I wanted to create a game similar to this (Slyway), but I had a problem with the child's movement, so I don't know what to use to do the movement during the draw. Is InputEventScreenTouch Or InputEventScreenDrag, all I come up with is this code that isn't working
extends KinematicBody2D
var velocity = Vector2.ZERO
var direction = Vector2.ZERO
var speed = 200
func input(event):
if event is InputEventScreenTouch:
if event.ispressed():
direction.x -= 1
func physicsprocess(delta):
if velocity.length() == 0:
_input(event)
velocity = Vector2.ZERO
velocity += direction * speed
velocity = moveand_slide (velocity)

Resources