在lua

时间:2018-06-05 18:41:44

标签: lua coordinates

我在这里编写了一个函数,它应该根据敌人坐标转换我的角色,但它并不完美,因为它并不总是转向我想要的地方,也许还有更好的写作方式

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 = "TURN RIGHT"
elseif xValue > 0 then
    xDir = "TURN LEFT"
end

if yValue < 0 then
    yDir = "TURN DOWN"
elseif yValue > 0 then
    yDir = "TURN UP"
end

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

print("Turn: " .. dir)

在这里你有一些照片可以进一步说明我的想法:

enter image description here

enter image description here

enter image description here

正如您在图片上看到的那样,方向取决于较高的数字。如果X高于Y(正值,负值和正值),则根据其是负还是正,将字符右转或左转。

1 个答案:

答案 0 :(得分:0)

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)