joining joints in corona using lua - lua

for i = 1,5 do
local link = {}
for j = 1,20 do
link[j] = display.newImage( "link.png" )
-
List item
link[j].x = 121 + (i*34)
link[j].y = 55 + (j*17)
physics.addBody( link[j], { density=2.0, friction=0, bounce=0 } )
-- Create joints between links
if (j > 1) then
prevLink = link[j-1] -- each link is joined with the one above it
else
prevLink = beam -- top link is joined to overhanging beam
end
myJoints[#myJoints + 1] = physics.newJoint( "pivot", prevLink, link[j], 121 + (i*34), 46 + (j*17) )
end
end
What does this mean?

From the Corona SDK's manual:
A pivot joint, known as a revolute joint in Box2D terms, joins two
bodies at an overlapping point, like two boards joined by a rotating
peg. The initial arguments are bodies A and B to join, followed by the
x and y coordinates for the anchor point, declared in content space
coordinates.
local pivotJoint = physics.newJoint( "pivot", bodyA, bodyB, anchor_x, anchor_y )
So the values you ask about are anchor coordinates (the point where both bodies are linked)
The number values are just values someone picked to make it look like he wanted it to.
Just alter them and see the links move!
That's a general advice. If you don't know what something does, refer to the manual and if you cannot break anything (which is the case pretty much always) try what happens if you change it.
That's the only way you can understand things.

Related

Gmod | Entity Spawning

if SERVER then
function SWEP:PrimaryAttack()
if self.Owner:GetEyeTrace().HitPos:Distance(self.Owner:GetPos()) < 100 then
local entity = ents.Create( "gred_emp_grw34" )
if ( !IsValid( entity ) ) then return end
entity:SetPos( self.Owner:GetEyeTrace().HitPos )
local entang = self.Owner:GetAngles()
entity:SetAngles(Angle(0, entang.y, 0) +Angle(0, 180, 0))
entity:SetModel("models/props_artillery/german/r_mortar_gw34.mdl" )
entity:Spawn()
self.Owner:StripWeapon( "turret_entplace" )
end
end
function SWEP:SecondaryAttack() end
end
This is my Code for spawning an entitiy with a Weapon now the problem is the Entity spawns in the floor so i am trying to add some Height to it can anyone help me with that?
The entity's position is self.Owner:GetEyeTrace().HitPos and because you are likely looking at the floor the entity spawn in the floor. I think you have something like this.
What you need to do is offsetting the position. It can be done like this :
local z_offset = 5 -- the offset you need (depends on the entity)
hitPos = self.Owner:GetEyeTrace().HitPos -- the position of the eye's hitting point
spawnPos = hitPos:Add(Vector(0, 0, z_offset) -- offset the pos
entity:SetPos( spawnPos )
Concerning the offset, i can't find anything (on the gmod wiki) to determine it... I think you will need to try different offset... Also, if you have other entities to spawn, you may also need to make a table with the different offsets.

Nested For-Loops - Remove Both Elements i and j

I'm using a game-making framework implemented in Lua to keep busy in quarantine. I'm making a simple platformer with ECS/DOP, and I wanted to generate collision geometry derived from a tilemap rather than just checking for collisions with all tiles.
Each tile has a bounding box component that points to a list that contains the basic shapes. Each shape stores the edges of the bounding box as {{x1,y1},{x2,y2}}. The first step in this process is to parse a TileMap table that contains only tilenames, then insert a copy of the corresponding bounding-box translated by the row/column * grid_dimension into a table named BBOX. The next step is to delete all instances of an edge if it is a duplicate illustrated by this image
which is where I'm stuck.
The desired, basic edge-deletion algorithm looks like this:
for i = #BBOX, 1, -1 do
local edge1 = BBOX[i]
for j = i, 1, -1 do
local edge2 = BBOX[j]
same_edge = edge1 == edge2 -- Not the actual comparison, just the outcome of it
if same_edge and i ~= j then
BBOX[i] = nil
BBOX[j] = nil
end
end
end
The issue is of course that this errors when i is equal to a j that was removed earlier in the loop. I've looked around and haven't been able to find a way to remove all instances of duplicate values in lua, only solutions that care about uniqueness. Has anyone found an efficient method of doing this or something similar?
If you use the value unique to each key you can better detect duplicates.
we will call this unique value edge.key.
If an edge will only exist at most twice then:
BBOX[edge.key] = BBOX[edge.key] == nil and edge or nil
will do the trick.
But where an edge may exist any arbitrary number of time we can do something like this:
local duplicateEdges = {}
for i = #BBOX, 1, -1 do
if BBOX[edge_key] then
duplicateEdges[edge_key] = true
else
BBOX[edge_key] = edge
end
for j = i, 1, -1 do
if BBOX[edge_key] then
duplicateEdges[edge_key] = true
else
BBOX[edge_key] = edge
end
end
end
for k in pairs(duplicateEdges) do
BBOX[k] = nil
end

Separating Axis Theorem function fails when met with acute angles

This is a little library I was making for the LOVE2D engine in Lua, which uses separating axis theorem to solve collisions.
I was so happy when I got my SAT program to work, and started testing it with a multitude of polygons. It works in most cases, and gives a correct minimum translation vector for them too. Oddly enough- if both shapes have acute angles, then those angles cause the program to fail, returning collisions when the shape isn't touching, or even more unusually, it gives a bizarre minimum translation vector. I have checked my function that returns normals- as I felt that this was my first point that could have failed, but it seems to be working fine.
This is the main function that handles my collision.
function findIntersection(shape1, shape2)
--Get axes to test.
--MTV means 'minimum translation vector' ie. the shortest vector of intersection
local axes1 = {}
local axes2 = {}
local overlap = false
local MTV = {direction = 0, magnitude = 99999}
for i, vert in pairs(shape1.hitbox) do
nrm = getNormal(shape1.hitbox, i)
table.insert(axes1, nrm)
end
for i, vert in pairs(shape2.hitbox)do
nrm = getNormal(shape2.hitbox, i)
table.insert(axes2, nrm)
end
--print(#axes1 .. ' ' .. #axes2)
--now that we have the axes, we have to project along each of them
for i, axis in pairs(axes1) do
test1 = hitboxProj(shape1, vectorToCoord(axis.direction, axis.magnitude))
test2 = hitboxProj(shape2, vectorToCoord(axis.direction, axis.magnitude))
if test2.max > test1.min or test1.max > test2.min then
if test2.max - test1.min < MTV.magnitude then
MTV.direction = axes1[i].direction
MTV.magnitude = test2.max - test1.min
end
else
return false
end
end
--now that we have the axes, we have to project along each of them
for i, axis in pairs(axes2) do
test1 = hitboxProj(shape1, vectorToCoord(axis.direction, axis.magnitude))
test2 = hitboxProj(shape2, vectorToCoord(axis.direction, axis.magnitude))
if test2.max > test1.min or test1.max > test2.min then
if test2.max - test1.min < MTV.magnitude then
MTV.direction = axes2[i].direction
MTV.magnitude = test2.max - test1.min
end
else
return false
end
end
return {MTV}
end
My project files are here on github https://github.com/ToffeeGoat/ToffeeCollision
It's a good start and your code is fairly clear. There are some things which can be improved, in particular I see that all of your functions are global. For starters you want to store all of your functions in a "module" to avoid polluting the _G space. You can use locals for everything else.
Note that it's not robust to write things like x == 0 this check will only work for integers and may fail when floating point math is involved. I recommend writing a simple test script for each function in your library.
Also, it's not efficient to write return {x = xCoord, y = yCoord} when you can return multiple values with Lua return xCoord, yCoord. Creating a lot of intermediate tables puts a strain on the garbage collector.
Some of your code needs reworking like the "getDirection" function. I mean there are already well-known techniques for this sort of thing. Check out my tutorial for examples: https://2dengine.com/?p=vectors#Angle_between_two_vectors
There is some silly stuff in there like function sq(x) return x*x end. Did you know you can write x^2 in Lua?
addDeg can be replaced by the modulo operator: newAng = (angle + addition)%360
Also note that there is absolutely no benefit to working with degrees - I recommend using only radians. You are already using math.pi which is in radians. Either way you have to pick either radians or degrees and stick to one or the other. Don't use both units in your code.
I don't want to nitpick too much because your code is not bad, you just need to get used to some of the best practices. Here is another one of my tutorials:
https://2dengine.com/?p=intersections

How can I get values from multiple instances of a class?

I am making a roguelike in Love2D as a hobby project. My approach is to try and use as much of the native capabilities of Lua and the Love2D (0.10.1) API as possible, without relying on fancy libraries like middleclass or HUMP, so as to learn more about the language.
After reading PiL's chapters on OOP and seeing the power there, I decided to set up a Mob class (using metamethods to emulate class functionality) that encompasses the players, monsters, and other NPCs (anything that can move). So, far, it's working beautifully, I can create all kinds of instances easily that share methods and all that stuff. But there's a lot of things I don't know how to do, yet, and one of them is holding my prototype up from further progress.
Setting up collision with the map itself wasn't too bad. My maps are tables full of tables full of integers, with 0 being the floor. The game draws "." and "#" and "+" and such to denote various inanimate objects, from each table. Player 1 moves using the numpad, and their position is tracked by dividing their raw pixel position by 32 to create a grid of 32x32 "tiles". Then, inside love.keypressed(key), I have lines like:
if key == "kp8" and currentmap[player1.grid_y - 1][player1.grid_x] == 0 then
player1.grid_y = player1.grid_y - 1
and so on, with elseifs for each key the player can press. This prevents them from walking through anything that isn't an open floor tile in the map itself.
But, I'm trying to implement some kind of "collision detection" to prevent MOBs from walking through each other and to use in writing the rules for combat, and this is trickier. I had a method in place to calculate the distance between mobs, but I'm told this might eventually cause rounding errors, plus it had to be written for each combination of mobs I want to test, individually.
What I'd like to know is: Is there a known (preferably elegant) way to get all instances of a particular class to pass some number of values to a table?
What I'd like to do is "ask" every Mob on a given map where they are, and have them "report" self.grid_x and self.grid_y to another layer of map that's just for tracking mobs (1 if self.is_here is true, 0 if not, or similar), that gets updated every turn. Then, I could implement collision rules based on coordinates being equal, or maybe a foo.is_here flag or something.
I have only vague ideas about how to proceed, however. Any help would be appreciated, including (and maybe especially) feedback as to a better way to do what I'm trying to do. Thanks!
A simple idea is to store "who is here" information for every cell of the field and update this information on every move of every object.
function create_game_field()
-- initialize a table for storing "who is here" information
who_is_here = {}
for y = 1,24 do
who_is_here[y] = {}
for x = 1,38 do
who_is_here[y][x] = 0
end
end
end
function Mob:can_move(dx, dy)
local u = currentmap[self.y + dy][self.x + dx]
local v = who_is_here[self.y + dy][self.x + dx]
if u == 0 and v == 0 then
return true
else
end
end
function Mob:move(dx, dy)
-- update "who is here"
who_is_here[self.y][self.x] = 0
self.x, self.y = self.x + dx, self.y + dy
who_is_here[self.y][self.x] = 1
end
function Mob:who_is_there(dx, dy) -- look who is standing on adjacent cell
return who_is_here[self.y + dy][self.x + dx] -- return mob or nil
end
function Mob:roll_call()
who_is_here[self.y][self.x] = 1
end
Usage example:
-- player1 spawns in at (6,9) on the grid coords
player1 = Mob:spawn(6,9)
-- player1 added to who_is_here
player1:roll_call()
Then, in love.keypressed(key):
if key == "kp8" and player1:can_move(0, -1) then
player1:move(0, -1)
end
There are a few ways you could get all your instances data but one of the simpler ones is probably to have them all be added to a table when they are created. Providing you add the entire table for that instance, all the values will update in the main table because it acts like a collection of pointers.
function mob:new( x, y, type )
self.x = 100
self.y = 200
self.type = type
-- any other declarations you need
table.insert(allMobs, self)
return self
end
Here we insert all the mobs into the table 'allMobs'. Once we have that we can simply iterate through and get all our coordinates.
for i, v in ipairs(allMobs) do
local x, y = v.x, v.y
-- Do whatever you need with the coordinates. Add them to another table, compare
-- them to others, etc.
end
Now we have a table with all our mobs in it and a way to access each of their positions. If you have any further inquiries then let me know.

Lua LÖVE automate variable names

I'm writing a lua LÖVE program as a school project.
The task is something about ants, that need to find food, take some to the nest they came from and on the way leaving a trace of pheromons. In addition we've write a program visualizing the process. For 100 ants, 5 food sources and all this in a space of 500x500 squares
I chose lua LÖVE for the visualization and wrote the following code:
function love.load()
p = 500 -- Starting position
xNest, yNest = p, p -- Initializing nest position
xAnt1, yAnt1 = p, p -- Initializing ant position
xAnt2, yAnt2 = p, p
end
-- Changes position every frame.
function love.update(dt)
-- AntI // See what I did there?
xAnt1 = xAnt1 + math.random (-2, 2) -- Change position by a random number between 2 steps forward and 2 steps backward
yAnt1 = yAnt1 + math.random (-2, 2) -- Change position by a random number between 2 steps sideways
xAnt2 = xAnt2 + math.random (-2, 2)
yAnt2 = yAnt2 + math.random (-2, 2)
end
-- Draw ants and nest.
function love.draw()
-- Nest
love.graphics.setColor(0, 255, 255) -- set drawing color green
love.graphics.rectangle("line", xNest, yNest, 2, 2) -- draw a nest at xNest, yNest with a size of 2x2
-- Ant
love.graphics.setColor(255, 255, 255) -- set drawing color white
love.graphics.rectangle("line", xAnt1, yAnt1, 2, 2) -- draw an ant at xAnt(number of ant), yAnt(number of ant) with a size of 2x2
love.graphics.rectangle("line", xAnt2, yAnt2, 2, 2)
end
Since my task is to do what I did in
xAntX, yAntX = p, p 100 times, whereby X I mean the number for the ant, I need some kind of loop that creates xAntX, yAntX = p, p, xAntX = xAntX + math.random (-2, 2) , yAntX = yAntX + math.random (-2, 2) and love.graphics.rectangle("line", xAntX, yAntX, 2, 2 a 100 times.
I tried a for loop, but it always yelled at me for trying to append a variable ´i´ to the initialization xAnt .. i, yAnt .. i and then count i++ with i = i + 1.
Make xAnt and yAnt tables, and access individual entries as xAnt[i] and yAnt[i].
While this question is quite old, if you're new to Lua and ended up here with the same question, I'd like to propose a different solution which is in my opinion more elegant than the accepted answer:
One simple method of storing multiple properties in a structured way is to store them as nested "object"-like tables in an "array"-like table. For example, initialise an empty ants table like so:
local ants = {}
Then, use a numeric for to add the desired amount of ants to the ants table:
for i = 1, 100 do
ants[#ants + 1] = { x: ..., y: ... }
end
Each ant itself is also a table, but instead of numeric keys, it uses string keys. See Lua's documentation on tables for more information. Now, you can loop over all the ants in the list and update each ant using:
for _, ant in ipairs(ants) do
ant.x = ant.x + math.random(-2, 2)
ant.y = ant.y + math.random(-2, 2)
end
Specific ants may be updated directly through their index. To update the second ant, use ants[2].
The benefit of this approach is that you only have one global variable which holds all your ants, instead of having separate global variables for each individual property of each ant. This generally makes the code easier to reason about and aids in debugging as well.
Happy developing fellow Luanatics :D

Resources