Lua中基于敌方坐标定位角色

我写了一个函数,应该会根据敌人坐标旋转我的角色,但它并不完美,因为它并不总是朝着我想要的方向旋转,也许有更好的编写方式。

local myPosition = {x = 350, y = 355}
local enemyPosition = {x = 352, y = 354}
local xValue, yValue, xDir, yDir, dir

if myPosition.x > enemyPosition.x then
    xValue = myPosition.x - enemyPosition.x
elseif myPosition.x < enemyPosition.x then
    xValue = myPosition.x - enemyPosition.x
else
    xValue = 0
end

if myPosition.y > enemyPosition.y then
    yValue = myPosition.y - enemyPosition.y
elseif myPosition.y < enemyPosition.y then
    yValue = myPosition.y - enemyPosition.y
else
    yValue = 0
end

if xValue < 0 then
    xDir = "向右转"
elseif xValue > 0 then
    xDir = "向左转"
end

if yValue < 0 then
    yDir = "向下转"
elseif yValue > 0 then
    yDir = "向上转"
end

if xValue > yValue then
    dir = xDir
elseif xValue
    dir = yDir
end

print("转向: " .. dir)

以下有一些图片来进一步说明我的想法:

进入图像描述


进入图像描述


进入图像描述

正如你在图片上看到的,方向取决于更高的数值。 如果X高于Y(无论是负值还是正值),那么就向右或向左旋转角色,具体取决于它是负值还是正值。

点赞
用户1847592
用户1847592

local myPosition = {x = 350, y = 355} local enemyPosition = {x = 352, y = 354}

local dx = enemyPosition.x - myPosition.x local dy = enemyPosition.y - myPosition.y local directions = {"TURN LEFT", "TURN DOWN", "TURN UP", "TURN RIGHT"} local dir = directions[(dx > -dy and 2 or 1) + (dx > dy and 2 or 0)] print("Turn: " .. dir)

```

本地变量 myPosition 被分配了一个包含 x 和 y 坐标的表,分别为 350 和 355。敌人变量 enemyPosition 同样类似地被分配了。计算出 dxdy 表示两个位置的 x 和 y 坐标之间的差。directions 变量是一个包含四个方向字符串的表。 dir 取决于 dx 和 dy 的值。如果 dx 大于 -dy 并且 dx 大于 dy,则 dir 被赋予表中的第二个元素 TURN DOWN。否则,dir 被赋予表中的第一个元素 TURN LEFT。

2018-06-05 19:12:39