Post #19: Click and Move Movement
Shower Thoughts
I've been posting small things I learn each day as I step into the world of game development. Today is post 19, which represents posting something small I've learned, every day, for 19 days straight! Thanks for following along so far.
I worry a bit about the depth I can achieve for a post every day. Due to a full time job and many other responsibilities in life, having a lot of time to dedicate to a super informative and helpful post is challenging. I really like the consistency of learning something every day, but worry that the small bites aren't really helpful to others.
I do have a potential solution to this, which keeps the consistency but helps with higher quality writing and sharing: adding a "writing" tab. I can continue making small posts as part of this blog, but then add another tab, where I do more formal writing on some game development topic. I haven't committed to this yet in any way; just brainstorming out loud! If you have any thoughts, please let me know.
Actual "Click and Move" Movement
In this post we're going to learn about the "click - and - move" movement style mentioned here.
In this, we need to have a player, and when the user clicks the mouse:
- We need to "catch" that input event
- We need to save the position of the mouse when they click
- Move the player to the saved position
Here is a small demo I put together:
Here is the code:
# ART CREDIT: https://simplepixelart.com/art/earth
extends CharacterBody2D
@export var speed = 300.0
var target
func _ready():
target = position
# This is called whenever there is an input event
func _input(event):
# Use is_action_pressed to only accept single taps as input instead of mouse drags
if event.is_action_pressed("click"):
target = get_global_mouse_position()
# Called once on each physics tick
func _physics_process(delta):
velocity = global_position.direction_to(target) * speed
#look_at(target)
if global_position.distance_to(target) > 10:
move_and_slide()