avoiding collision in corona sdk - coronasdk

How to avoid collision between physics bodies in corona ? The application that I am developing makes use of many physics bodies.I want collision to happen between two desired bodies,but the collision is happening between all the bodies in the system.Can anyone help me with a solution?

You need to create a 'collision filter' adding both 'categoryBits' and 'maskBits' to every object. You assign a number to both them in physics body. Something like:
physics.addBody(object, {bounce = .2, density = 1, filter = {maskBits = 2, categoryBits = 4}})
Mask bits will only collide with an objects with same category bit.
So an object with maskBit = 2 will only collide with an object with a categoryBit = 2.
You can assign any number you want as far a I know.

There is the second method to assign a groupIndex to each object. The value can be a positive or negative integer, and is a simpler way of specifying collision rules: objects with the same positive groupIndex value will always collide with each other, and objects with the same negative groupIndex value will never collide with each other.
local collisionFilter = { groupIndex = 2 }
physics.addBody(object1, {bounce = .2, density = 1, filter = collisionFilter})
physics.addBody(object2, {bounce = .2, density = 1, filter = collisionFilter})

The concept is Collision Filtering. This link might help.
http://developer.anscamobile.com/forum/2010/10/25/collision-filters-helper-chart

The numbers need to be in powers of 2. Not any number.

I know this has already been answered but this might be useful for you. I used object.isSensor = true on my project so that even if the object has a physics body, it won't collide with other objects.

Related

Making a rectangle jump? (Love2d)

I might be stupid or something. But, I'm having a hard time with this. I usually find examples of code but it just confuses me. Unfortunately there isn't any good tutorial for this. I been using Lua for almost a year so I kinda have experience. Help would be extremely appreciate!
Basically I want to learn how to make rectangle jump up and then go back down.
For a single block that you control, you essentially need to store it's gravity and figure out a nice acceleration for it.
currentGravity = 0;
gravity = 1;
Then in the loop, you have to check if it's on ground using some collision detection. You want to add the gravity acceleration to currentGravity:
currentGravity = currentGravity + gravity
Then, you add it to the current y axis of the block:
YAxis = YAxis + currentGravity
Once you land, make sure to set gravity to 0. Also be sure to keep setting it to 0 to ensure you don't fall through the ground (as you kept adding to gravity no matter what.)
if not inAir() then
currentGravity = 0
end
And, of course, to jump, set currentGravity to a negative number (like 20) (if that's how you made the gravity work.)
Here's a collision detection function I made for Love2D:
function checkCollision(Pos1,Size1,Pos2,Size2)
local W1,H1,W2,H2 = Size1[1]/2,Size1[2]/2,Size2[1]/2,Size2[2]/2
local Center1,Center2 = {Pos1[1]+W1,Pos1[2]+H1},{Pos2[1]+W2,Pos2[2]+H2}
local c1 = Center1[1]+(W1) > Center2[1]-W2
local c2 = Center1[1]-(W1) < Center2[1]+W2
local c3 = Center1[2]+(H1) > Center2[2]-H2
local c4 = Center1[2]-(H1) < Center2[2]+H2
if (c1 and c2) and (c3 and c4) then
return true
end
return false
end
It assumes the position you gave it is the center of the block. If the box is rotated it won't work. You'll have to figure out how to make it work with walls and the like. And yes, it's ugly because it's very old. :p

What are Sprite Kit's "Category Mask" and "Collision Mask"?

I am following the Sprite Kit guide, and in the scene editor it asks me to set the Category Mask to 32 and Collision Mask to 11. How are these numbers related?
The Category bit mask tells Sprite-Kit what sort of object this is.
The Collision bit mask tells Sprite Kit what objects this object
collides with (i.e. will hit and bounce off).
The ContactTest bit mask tells Sprite-Kit what contacts you want to
be notified about i.e. when this object touches another object.
Collisions are handled automatically by the Sprite-Kit game engine; contacts are handled by your code - when a contact happens that you are interested in, your code (didBeginContact'for Swift 2,'didBegin(contact:) for Swift 3 and later) is called.
You need to think of these bitmasks in binary and for simplicity, we'll start with simple category bit masks, whereby each object in your scene belongs to only one category.
E.g. in your scene you have a player, a player-missile, an enemy and the screen-edge. We'll assume that the bit masks are 8-bit instead of 32-bit. Think of each number as a range of 8 binary digits (8 bits) each of which is a 0 or 1.
The objects in your scene have to have unique categories, so we'll assign them as follows:
player.categoryBitMask = 00000001 (1 in decimal)
playerMissile.categoryBitMask = 00000010 (2 in decimal)
enemy.categoryBitMask = 00000100 (4 in decimal)
screenEdge.categoryBitMask = 00001000 (8 in decimal)
If you use numbers that are, in decimal, something other than a power of 2 (1, 2, 4, 8, 16, 32, 64, 128 etc) then more than 1 bit will be set in the category bit mask which complicates things (it means that this object belongs to multiple categories) and your code has to get more complicated.
Now think about what bounces off what (the collisions). Let's say everything bounces off everything else except the missile goes through the screen edge.
The collision bit masks for each object consists of the bits that represent the objects that this object collides with i.e.:
player.collsionBitMask = 00001111 (15 in decimal) (the bits for all other objects are set)
playerMissile.collisionBitMask = 00000111 (7) (all object EXCEPT screenEdge)
enemy.collisonBitMask = 00001111 (15) (everything)
screenEdge.collisonBitMask = 00000000 (0) (collides with nothing)
Now we think about which object interactions we are interested in. We want to know when:
player and enemy touch
enemy and player touch or the enemy and the player's missile touch.
This is represented by:
player.contactTestBitMask = 00000100 (4) (the enemy's categoryBitMask)
enemy.contractTestBitMask = 00000011 (3) (the player's categoryBitMask combined with the missile's categoryBitMask))
Note that if you want to know when A and B touch, it's enough just to have A's contactTestBitMask (CTBM) to include B's categoryBitMask; you don't have to have B's CTBM set to A's category too. But if you want them to bounce off each other, then each object's collisionBitMask must include the other's categoryBitMask. If A's collisonbitMask includes B's category, but not vice versa, then when the 2 collide, A will bounce off but B will be unaffected by it.
For your specific example, (Category Mask to 32 and collision mask to 11), the categoryBitMask is 32 which is 00100000 (sticking with only 8 bits). The collisionBitMask is 11, which is 8 + 4 + 1 so in binary this is '00001101' which means it collides with objects with a categoryBitMask of 8, 4 or 1, so I assume that there are objects in your scene with these categoryBitMasks.
By default everything bounces off everything else i.e. the collisionBitMask is all '1's i.e. b'111111..' and nothing notifies of contacts with anything else i.e. contactTestBitMask is all '0's.
Also - all of this applies to physicsBodies, not nodes.

I joined multiple images into a rope. How can I decrease the rope stretchiness?

I created a rope based off this tutorial, except my rope has one ball attached on each end of the rope.
High Level: This is how they create the rope.
create an array of SKNodes
append each rope segment (node) to the array
add each node to the screen
join each node together to form a rope
(Then I add a ball on each end of the rope)
In my program I move the ball around and basically swing the rope around kind of like a stretchy pendulum.
Here's my issue: If I swing the rope around very hard, the rope stretches too much! How can I decrease the amount the rope stretches? I don't see a method to decrease the elasticity of the body.
If there is any other information that will be useful please let me know! Thanks in advance
You can try these two methods. The first method is to increase the property frictionTorque of SKPhysicsJointPin class.
The range of values is from 0.0 to 1.0. The default value is 0.0. If a
value greater than the default is specified, friction is applied to
reduce the object’s angular velocity around the pin.
An example for the tutorial you followed, before adding a joint to the scene, modify frictionTorque:
for i in 1...length {
let nodeA = ropeSegments[i - 1]
let nodeB = ropeSegments[i]
let joint = SKPhysicsJointPin.jointWithBodyA(nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
anchor: CGPointMake(CGRectGetMidX(nodeA.frame), CGRectGetMinY(nodeA.frame)))
joint.frictionTorque = 0.5 // Add this line
scene.physicsWorld.addJoint(joint)
}
The second method is to limit the swing angle of the pin joint. After enabling shouldEnableLimits, adjust lowerAngleLimit and upperAngleLimit in radians.
Read more about SKPhysicsJointPin Class Reference for Determining the Characteristics of the Pin Joint.

How to get updated positions in Lua

I have 2 classes, In one class, I have code for position of object1 changing with time and in class2, I have code for object2 changing with time, the positions are changing continuously at different rates. Now, I want to figure out if the two objects collide, but how do I get their positions that are changing at difference of less tahn a second, is their any shortcut or efficient method to do that?
Here is how object1 and object 2 are changing their positions:
object 1:
self:setRotation( self:getRotation() + math.random(5,7) )
object2:
x = 215 + math.cos(angle)*195
y = 130 + math.sin(angle)*115
Both of these are part of 2 different classes. I need to use them in a third lua file where I am checking for the collisions, so how can I get x and y value of both of these as soon as it changes and pass them to a new function to check for collisions
I have 2 classes, In one class, I have code for position of object1 changing with time and in class2, I have code for object2 changing with time, the positions are changing continuously at different rates. Now, I want to figure out if the two objects collide, but how do I get their positions that are changing at difference of less tahn a second, is their any shortcut or efficient method to do that?
Here is how object1 and object 2 are changing their positions:
object 1:
self:setRotation( self:getRotation() + math.random(5,7) )
object2:
x = 215 + math.cos(angle)*195
y = 130 + math.sin(angle)*115
Both of these are part of 2 different classes. I need to use them in a third lua file where I am checking for the collisions, so how can I get x and y value of both of these as soon as it changes and pass them to a new function to check for collisions
Here is how I tried to use Collision detection using TNT
--> let's say I group all my 3 clock hands, these are rotated around an anchor point so x and y remain the same, but they have some width extending,
--> My player is moving in an ellipsis and it's position is changing with time(only when the player jumps, it's not on floor)
Requirement--> what I really want is whenever the player touches any of the clock hands, youLoose method(not given in the code) shall be called, now to achieve this, here is what I did:
and the collision can be anywhere across the length of any of the clock hands,(so basically this part is what I am not getting)
I checked collision as soon as x and y of player changed,here is the code:
attaching the image as well
x = 215 + math.cos(angle)*195
y = 130 + math.sin(angle)*115
for i = 1, groupA:getNumChildren() do
local sprite2 = groupA:getChildAt(i)
local oBoxToObox = tntCollision.oBoxToObox
if i == 1 then
a = 97
b = 11
elseif i == 2 then
a = 206
b = 64
else
a = 120
b = 10
end
local pointToObox = tntCollision.pointToObox
tntCollision.setCollisionAnchorPoint(0, 0)
if oBoxToObox(x,y, 36, 40, cute.anim[self.frame]: getRotation(),sprite2:getX(), sprite2:getY(), a ,b, sprite2:getRotation()) then
youLoose()
end
end
If the objects have volume you need to test if their boundaries cross, quite complicated, and you should use either Box2d or TNT Collision. Both integrated to Gideros (although TNT is a separate download). TNT Collision is only collision, no physics, so likely to be faster but not necessarily so, you would have to compare.
Otherwise (no volume, ie just point collisions), you can just test the x coordinate of each object; if almost identical, then check the y coord; if almost identical you have a collision, otherwise you don't.

Corona/Box2D detect collision with non-moving static objects

For posting reasons here's a simple version of what I'm trying to do.
On the screen I have a simple circle object that is static and doesn't move. The user can then drag and drop a straight line. If the line passes through that circle I'm hoping for the collision event to be triggered.
It appears that unless one of the objects are moving the collision is never detected. Can I detect the collision when the line is drawn?
Collision Event
function onHit(e)
print("hit");
end
Runtime:addEventListener("collision", onHit)
Touch Event
local startX = 0;
local startY = 0;
local endX = 0;
local endY = 0;
function onTouch(e)
if(e.phase == "began") then
startX = e.x
startY = e.y
elseif(e.phase == "moved") then
endX = e.x
endY = e.y
elseif(e.phase == "ended") then
local line = display.newLine(startX, startY, endX, endY)
line:setColor(100, 100, 100)
line.width = 2
physics.addBody(line, "static", { })
end
end
Runtime:addEventListener("touch", onTouch)
Create circle
local c = display.newCircle(50, 50, 24)
physics.addBody(c, "static", { radius = 24 })
This page from the Corona SDK docs describes the bodyType property about halfway down the page. When describing "static" bodies, it says (my emphasis):
static bodies don't move, and don't interact with each other;
examples of static objects would include the ground, or the walls of a
pinball machine.
That means that one of the objects has to be something other than static.
Here's an idea, although I haven't tried it myself: (See update below.) Make the line dynamic when you first create it. Set it to static a few milliseconds later using a timer.performWithDelay function. If a collision event occurs in the meantime, you will know that you've got an overlap, and can set the bodyType back to static immediately. If you don't get a collision event, the bodyType will still be dynamic in the delayed routine, and you'll know you didn't have an overlap. In this case, you'll still need to set the line to static in the delayed routine.
UPDATE: Tested this, using your code as the starting point
I changed the collision event to always set both objects' bodyType to static:
function onHit(e)
print("hit")
e.object1.bodyType = "static"
e.object2.bodyType = "static"
end
Then I changed the addBody call for the line to add it as a dynamic body, with new code to setup a timer.PerformWithDelay function to check after a short time:
physics.addBody(line, "dynamic", { })
timer.performWithDelay(10,
function()
if line.bodyType == "dynamic" then
print ("NO OVERLAP")
line.bodyType = "static"
end
end)
The results were, unfortunately, mixed. It works most of the time, perhaps 95%, but fails occasionally when drawing a line that starts outside the circle and ends inside, which should be an overlap, but is sometimes reported as no overlap. I wasn't able to figure out why this was happening. I'm posting this anyway, hoping that it gets you going, and also thinking that someone may be able to figure out the inconsistent behavior and educate us both.
Failing that, you could add an additional check for the "no overlap" case to check if either endpoint of the line is closer than the radius of the circle away from the center. That would be make things work, but I suppose it misses the whole point of letting the physics engine to the work.
Anyway, good luck!
Perform a raycast when you release your mouse press. This way you can keep both objects static, and know that they intersect via the raycast callback.
(I know that this is an old post, but it was the first hit on my Google search and is incorrect afaic)
Set the body type as kinematic, set it as a sensor, and update its position to the entity it's tied to every frame. Unlike static, kinematic can interact with static.

Resources