Dot
Name
Type
Description
Type
Description
-- entity.lua
local function init(self)
self.Physics = true
local box_shape = api.physics.NewBoxShape(1, 1, 1)
local box = api.physics.NewBody(box_shape, 1)
self.Body = box
self.Data.direction = {
{cardinal = "North", minimum = 315, maximum = 45},
{cardinal = "East", minimum = 45, maximum = 135},
{cardinal = "South", minimum = 135, maximum = 225},
{cardinal = "West", minimum = 225, maximum = 315}
}
end
local function update(self, dt)
local north = api.physics.NewVector(0,1,0)
local east = api.physics.NewVector(1,0,0)
local west = api.physics.NewVector(-1,0,0)
local vector = api.physics.NewVector(
math.random()-0.5,
math.random()-0.5,
math.random()-0.5
)
local dot_product = north:Dot(vector)
local combined_magnitudes = north:Magnitude() * vector:Magnitude()
local radians = math.acos(dot_product / combined_magnitudes)
local degrees = radians * 180 / math.pi
local is_reflex_angle = east:Dot(vector) <= west:Dot(vector)
if is_reflex_angle then
degrees = 360 - degrees
end
local cardinal = ""
for index, direction in ipairs(self.Data.direction) do
if direction.cardinal == "North" then
if direction.minimum <= degrees or direction.maximum > degrees then
cardinal = direction.cardinal
break
end
else
if direction.minimum <= degrees and direction.maximum > degrees then
cardinal = direction.cardinal
break
end
end
end
local degrees_rounded = math.floor(degrees)
print("This entity is moving "..degrees_rounded.." degrees from "..
"the north direction. Its orientation is "..cardinal..".")
self.Body:ApplyForce(vector)
end
-- Turn on physics calculations for this entity.
-- Create a box shape and a body. Assign it to the entity.
-- Define ranges for all the cardinal directions.
-- Every update, define vectors for the north, east, and west directions.
-- Create a randomised vector for the direction of the entity's movement.
-- Use the dot product to calculate the angle between the random vector and north.
-- The angle will always be between 0 and 180 degrees.
-- Compare the similarity of the east and west directions with the vector.
-- If more westerly, calculate the clockwise reflex angle from the anticlockwise angle.
-- Check if the angle fits between a minimum and maximum for each cardinal range.
-- Adjust the check for the North range, since it wraps around from 315 to 45.
-- Identify and print the cardinal direction of the entity's movement.
-- Prints:
-- This entity is moving 326 degrees from the north direction. Its orientation is North.
-- This entity is moving 253 degrees from the north direction. Its orientation is West.
-- This entity is moving 120 degrees from the north direction. Its orientation is East.
-- This entity is moving 219 degrees from the north direction. Its orientation is South.
-- This entity is moving 223 degrees from the north direction. Its orientation is South.
-- ...Last updated