Created
July 29, 2023 04:37
-
-
Save mkdym/ee175c1e72de50da9f520733ffbc8bdf to your computer and use it in GitHub Desktop.
Godot 精灵移动不超出边界
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Sprite | |
export var speed = 400 | |
# Called when the node enters the scene tree for the first time. | |
func _ready(): | |
pass | |
# Called every frame. 'delta' is the elapsed time since the previous frame. | |
func _process(delta): | |
var vec = Vector2.ZERO | |
if Input.is_action_pressed("move_right"): | |
vec.x += 1 | |
if Input.is_action_pressed("move_left"): | |
vec.x -= 1 | |
if Input.is_action_pressed("move_up"): | |
vec.y -= 1 | |
if Input.is_action_pressed("move_down"): | |
vec.y += 1 | |
vec = vec.normalized() * speed # 单位向量乘以速度 = 单位时间应该移动的向量距离 | |
self.position += vec * delta # 乘以时间表示移动的距离 | |
# 避免超出边界 | |
var screenSize = get_viewport_rect().size | |
self.position.x = clamp(self.position.x, 0, screenSize.x) | |
self.position.y = clamp(self.position.y, 0 , screenSize.y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment