Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Math 使用三角学通过鼠标位置计算移动角度_Math_Lua_Game Physics_Trigonometry - Fatal编程技术网

Math 使用三角学通过鼠标位置计算移动角度

Math 使用三角学通过鼠标位置计算移动角度,math,lua,game-physics,trigonometry,Math,Lua,Game Physics,Trigonometry,我正在用Lua构建一个游戏以获得乐趣(即使你不了解Lua,你也可以帮助我,因为它适用于任何编程语言)。我的问题是我在一个表中为玩家定义了一个x和y变量: player = {} player.x = 10 player.y = 10 player.velocity = 50 我的目标是让玩家移动到屏幕上鼠标的位置。目前,我已将其设置为根据鼠标位置增加/减少每次更新的x值和y值。我的代码如下所示: function update(delta_time) -- delta_time is tim

我正在用Lua构建一个游戏以获得乐趣(即使你不了解Lua,你也可以帮助我,因为它适用于任何编程语言)。我的问题是我在一个表中为玩家定义了一个x和y变量:

player = {}
player.x = 10
player.y = 10
player.velocity = 50
我的目标是让玩家移动到屏幕上鼠标的位置。目前,我已将其设置为根据鼠标位置增加/减少每次更新的x值和y值。我的代码如下所示:

function update(delta_time)  -- delta_time is time in milliseconds since last update
  if mouse.x > screen.width and mouse.y < screen.height then
    player.x = player.x + player.velocity * delta_time
    player.y = player.y + player.velocity * delta_time
end
函数更新(delta_-time)——delta_-time是自上次更新以来的时间(以毫秒为单位)
如果mouse.x>screen.width,mouse.y
这只是我要定义的一个方向的一个例子。我的问题是,我不想让巨大的流量控制块检查鼠标的x和y位置在哪个象限,并相应地调整玩家的x和y位置。我宁愿有一个流体360度检测,可以移动玩家的角度鼠标定位从中心


另一个问题是,当我将玩家移动到屏幕右侧时,我只会增加x值,但当我将玩家移动到屏幕的东北侧时,我会增加x和y值。这意味着玩家的速度将提高2倍,这取决于移动角度的精细程度。当我做出东北-东角度和西北-西角度时,玩家的速度现在快了3倍,因为我增加/减少了y 2和x 1。我不知道如何解决这个问题。我真的很擅长数学和三角,但我不擅长把它应用到我的游戏中。我只需要有人帮我开灯,我就会明白。如果您真的阅读了所有这些,感谢您抽出时间。

计算从玩家位置到鼠标位置的向量。规范化该向量(即,除以其长度),然后乘以player.velocity,然后将其添加到player.x和player.y。这样,速度是恒定的,你可以在各个方向上平稳移动

-- define the difference vector
vec = {}
vec.x = mouse.x - player.x
vec.y = mouse.y - player.y

-- compute its length, to normalize
vec_len = math.pow(math.pow(vec.x, 2) + math.pow(vec.y, 2), 0.5)

-- normalize
vec.x = vec.x / vec_len
vec.y = vec.y / vec_len

-- move the player
player.x = player.x + vec.x * player.velocity * delta_time
player.y = player.y + vec.y * player.velocity * delta_time

你认为你可以使用pastebin链接到所有的代码吗?@Coffee我作为例子展示的if语句是不够的?它只检查鼠标所在的象限,并为每次更新相应地增加/减少x和y值。如果你需要我详细说明游戏的具体部分,我可以;让我知道。好的,nvm-我想这应该足够了。你能给我举个例子吗?我在上高中,我正在为一个计算机科学夏令营制作这个游戏。不幸的是,我还没有学到任何关于向量形式的知识。您甚至可以使用另一种编程语言,如C或Python作为示例。添加的代码(不确定lua语法,但我希望您能理解这一点)成功了。幕后的math实际上在做什么?一些代码改进:1)可以在表构造上设置向量字段2)math.pow函数可以用操作符替换
^
3)
math.pow(?,0.5)=math.sqrt(?)