Reputation: 31
I tried to make an input program by using the math. libraries (along with the arctan ofc), but it somehow brings the same result, regardless of the "position" given in the option 1 (500 for the distance and 88. or 89. for the angle)
math.randomseed (os.time())
local player_choice = 0
local Player_x, Player_y = 400,300
local Enemy_x, Enemy_y = 0,0
while player_choice ~= 4 do
print ("+=======================================+")
print (" WELCOME, "..os.date())
print (":---------------------------------------:")
print (": 1. Generate enemy random position. :")
print (": 2. Distance from enemy to the player :")
print (": 3. Get angle from enemy to the player :")
print (": 4. Exit :")
print ("+=======================================+")
print ("please, select your option above:")
local player_choice = io.read ("*n")
if player_choice == 1 then
local Enemy_x = math.random (0,800)
local Enemy_y = math.random (0,600)
print ("new enemy position: ["..Enemy_x..","..Enemy_y.."]")
end
if player_choice == 2 then
local distance = math.sqrt((Enemy_x - Player_x)^2 + (Enemy_y - Player_y)^2)
print ("distance from Enemy to the Player: ".. distance)
end
if player_choice == 3 then
local angle = math.atan (Enemy_y - Player_y - Enemy_x - Player_x)
local angle_degree = math.deg (angle)
print ("The angle from Enemy to the Player: ".. angle_degree.." degree.")
end
end
Is there any way to resolve this code or is it a flaw from the version itself? (i watched from an older version tutorial)
Upvotes: 0
Views: 203
Reputation: 28974
There are two issues with your code.
Issue 1:
You random enemy position is local to this if statement:
if player_choice == 1 then
local Enemy_x = math.random (0,800)
local Enemy_y = math.random (0,600)
print ("new enemy position: ["..Enemy_x..","..Enemy_y.."]")
end
You do not change to what you defined here local Enemy_x, Enemy_y = 0,0
Outside that if block Enemy_x
and Enemy_y
are still 0
.
Defining those local variables in the if block shadows the variables of the same name defined in a larger scope.
You need to remove the local
keywords in the if statement.
if player_choice == 1 then Enemy_x = math.random (0,800) Enemy_y = math.random (0,600) print ("new enemy position: ["..Enemy_x..","..Enemy_y.."]") end
This explains why your distance is always 500
and part of why your angle never changes.
Issue 2:
The angle between two points is not calculated from the difference of their coordinates as in
local angle = math.atan (Enemy_y - Player_y - Enemy_x - Player_x)
Maybe a typo?
You should actually calculate math.atan(Enemy_y - Player_y, Enemy_x - Player_y)
As a result of that your code always calculates math.atan(-700)
which results in an angle that does not change.
I suggest you give https://en.wikipedia.org/wiki/Atan2 another read.
Upvotes: 2