英文:
I tried to shoot an object towards cursor position, but it has a problem
问题
我是Godot的新手,我想要将一个已经在游戏中的对象射向鼠标光标位置,我为此创建的方法可以正常工作,但根据对象和光标之间的距离,速度会改变。有人可以帮助我让速度保持恒定吗?
我使用了以下代码:
func _process(_delta):
if Input.is_action_just_released("tap"):
var mousepos = get_viewport().get_mouse_position()
var ballpos = self.get_position()
var x = mousepos.x - ballpos.x
var y = mousepos.y - ballpos.y
velocity = Vector2(x, y)
英文:
I'm a beginner in Godot I want to shoot an object that is already in the game towards where the cursor's position is, and the method I created for it works fine but depending on the distance between the object and the cursor the speed changes. can anyone please help me make the speed constant?
I used this:
func _process(_delta):
if Input.is_action_just_released("tap"):
var mousepos = get_viewport().get_mouse_position()
var ballpos = self.get_position()
var x = mousepos.x - ballpos.x
var y = mousepos.y - ballpos.y
velocity = Vector2(x,y)
答案1
得分: 1
你可以将向量标准化,得到一个单位长度的向量:
速度 = Vector2(x,y).normalize()
然后按照你想要的速度进行缩放:
速度 = Vector2(x,y).normalize() * 速度值
其中速度值是之前定义好的变量或常量。类似这样会起作用:
var 速度值 := 100.0
当然,你可能会想要调整这个值。所以也许你想要将其导出以便在检查器中设置:
export var 速度值 := 100.0
顺便说一下,你可以将你已有的代码改写成这样:
var 鼠标位置 = get_viewport().get_mouse_position()
var 球位置 = self.get_position()
速度 = 鼠标位置 - 球位置
在以上建议的基础上进行更改,我们得到:
var 鼠标位置 = get_viewport().get_mouse_position()
var 球位置 = self.get_position()
速度 = (鼠标位置 - 球位置).normalize() * 速度值
你也可以将其改写成:
var 鼠标位置 = get_viewport().get_mouse_position()
var 球位置 = self.get_position()
速度 = 球位置.direction_to(鼠标位置) * 速度值
英文:
You can normalize your vector, which gives you a vector of unit length:
velocity = Vector2(x,y).normalize()
And then scale it by the speed you want:
velocity = Vector2(x,y).normalize() * speed
Where speed is a previously defined variable or constant. Something like this will do:
var speed := 100.0
You, of course, will want to tweak the value. So perhaps you want to export it so you can set it form the inspector:
export var speed := 100.0
By the way, you can rewrite the code you have to this:
var mousepos = get_viewport().get_mouse_position()
var ballpos = self.get_position()
velocity = mousepos - ballpos
Adding the changes suggested above we have:
var mousepos = get_viewport().get_mouse_position()
var ballpos = self.get_position()
velocity = (mousepos - ballpos).normalize() * speed
Which you can rewrite to this:
var mousepos = get_viewport().get_mouse_position()
var ballpos = self.get_position()
velocity = ballpos.direction_to(mousepos) * speed
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论