lua - 根据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(负值和正值),则将字符向右或向左旋转,具体取决于它是负数还是正数。
解决方案
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)
推荐阅读
- javascript - 如何从Angular中的函数导出变量?
- docusignapi - 如何使用嵌入式签名并将电子邮件发送给其他收件人 Docusign?
- javascript - 在 javascript 中, ! 在数组括号前签名吗?
- c# - 当 App A 的身份验证失败时,.NET OpenIdConnect 重新向 App B 进行身份验证
- regex - 删除新行,但如果包含在文本边界内则不删除
- c++ - 当 QObject 通过引用传递时,C++ 信号的参数在 QML 中显示为“未定义”
- elasticsearch - 如何在弹性搜索匹配查询中提升单个单词
- php - 查找至少 10 个字符的 src 属性
- .net - 如何计算 JObject 的唯一 Hashcode
- python - python解析xml获取值