首页 > 解决方案 > 根据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 = "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)

在这里你有一些图片来进一步说明我的想法:

在此处输入图像描述


在此处输入图像描述


在此处输入图像描述

正如您在图片中看到的,方向取决于较大的数字。如果 X 高于 Y(负值和正值),则将字符向右或向左旋转,具体取决于它是负数还是正数。

标签: luacoordinates

解决方案


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)

推荐阅读