天下程序员首页cx06.com
管理 |  登录 |  注册
袁鹏飞的小屋
笔记(共39个) > godot学习

godot的2D运动

阅读 1赞 0回复 2024-07-08 23:09:22

../../_images/movement_click.gif

extends CharacterBody2D

@export var speed = 400

var target = position

func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			target = get_global_mouse_position()

func _physics_process(delta):
	velocity = position.direction_to(target) * speed
	# look_at(target)
	if position.distance_to(target) > 10:
		move_and_slide()

注意我们在移动之前做的 distance_to() 检查. 如果没有这个检查, 物体在到达目标位置时会 "抖动", 因为它稍微移过该位置时就会试图向后移动, 只是每次移动步长都会有点远从而导致来回重复移动.

如果你喜欢, 取消注释的 rotation 代码可以使物体转向其运动方向.


赞(1)

文章作者置顶的回复

全部回复列表 当前第(1)页

添加回复,文明发言,会审核.(服务区回复可以发广告)

作者最新笔记
天下程序员 www.cx06.com 程序员的网上家园!
作者微信:13126507001