Making physics bodies responsive to fields but not to other physics bodies - ios

In my game I have a body that flies across the screen, and is supposed to be affected by a radial gravity field that I have created. To do this, I needed to turn the
body.dynamic = true
But this results in the body colliding with other objects (with physics bodies) that are on the screen, when I just want it to be affected by the field and not by these objects. If I turn the
body.dynamic = false
then it doesn't get affected by the field.
What should I do to make the body stay on its path?
EDIT This is my code for the main body that flies across the screen, after a node has already been created
body.physicsBody = SKPhysicsBody(rectangleOfSize: rectangle)
body.physicsBody?.dynamic = true
body.physicsBody?.categoryBitMask = PhysicsCategory.body
body.physicsBody?.contactTestBitMask = PhysicsCategory.otherBody
body.physicsBody?.affectedByGravity = false
body.physicsBody?.fieldBitMask = PhysicsCategory.shield
body.physicsBody?.allowsRotation = false
The image shows the 2 possible ways I want the body to avoid colliding with the object. Either it can pass through it, or it can pass around it and return to the earlier path. How do I do that?

You should set
body.physicsBody?.collisionBitMask = 0
collisionBitMask - A mask that defines which categories of physics bodies can collide with this physics body. IF the value is not set your PhysicsBody collides with every other PhysicsBodies, If value is set to 0 your PhysicsBody do not collide with other PhysicsBodies
I you set collisionBitMask = 0 your body node will go through all other nodes, if you whant it to collide you need to set node physicsBody?.collisionBitMask (for example if you whant your node to collide only with ball and wall physicsBody?.collisionBitMask = kCategoryWall | kCategoryBall)
I hope it was helpfull

Related

How to set category mask in sprite kit?

let dart = SKSpriteNode(imageNamed: "Dart")
dart.physicsBody?.isDynamic = true
dart.physicsBody?.categoryBitMask = 3
dart.physicsBody?.collisionBitMask = 2
when I print the darts category masks it returns nil. I have set other sprites category masks through the scene editor and they work fine. Thanks for any help.
You haven't actually made a physics body.
dart.physicsBody = SKPhysicsBody(...)
dart.physicsBody?.isDynamic = true
// etc.
The ... depends on the type of physics body you want (circle, rectangle, polygon, etc.) See examples here:
https://developer.apple.com/documentation/spritekit/sknode/getting_started_with_physics_bodies

How to make a Sprite an obstacle for another Sprite?

I am making a game with sprites that move and obstacles to learn SpriteKit. I want the sprites that move to collide with the obstacles and bounce off of them but I want the obstacles to stay fixed. How do I do this? I have tried the following with no success:
Setting obstacle.physicsBody?.isDynamic = true. This made the sprites go through the obstacle.
Fixing the movement and rotation of the object with SKConstraint. When I do this they just go through each other.
Setting the mass of the body to be really high as follows obstacle.physicsBody?.mass = CGPoint.maxFiniteMagnitude but this freezes the game. When I set it really high it doesn't seem to do anything.
Setting obstacle?.physicsBody.velocity = CGVector(dx: 0, dy: 0) when the objects collide. I know that the contact.bodyA and contact.bodyB are passed by value and not reference so I loop through an array with the obstacles and set the velocity this way. The obstacles are still pushed by the other sprites.
Update:
- Setting obstacle.physicsBody?.collisionBitMask = PhysicsCategory.none so the sprite collides with the obstacle but not the other way around.
The object is setup as follows, with fish being the other sprite:
obstacle.position = location
obstacle.physicsBody = SKPhysicsBody(rectangleOf: obstacle.size)
obstacle.physicsBody?.isDynamic = true
obstacle.physicsBody?.categoryBitMask = PhysicsCategory.obstacle
obstacle.physicsBody?.contactTestBitMask = PhysicsCategory.fish
obstacle.physicsBody?.collisionBitMask = PhysicsCategory.fish
obstacle.physicsBody?.usesPreciseCollisionDetection = true
self.obstacles.append(obstacle)
super.addChild(obstacle)
Please let me know if there is something I am doing wrong / misunderstanding. Thanks.
Found the answer here. One of the objects needs to have .physicsBody?.isDynamic = true. In this case I set the obstacle to false so it is stationary.

iOS Collision Detection

I have tried and tried to get collision detection to work the way I need but to no avail. What I want to accomplish is to get notified when the character touches an object but not stop it from moving on to the object. In GameScene, I have the physics of the object set like this:
Category Mask: 8
Collision Mask: 0
Field Mask: 0
Contact Mask: 0
I add the character to the scene in my code. I have a category structure like this:
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1 // 1
static let Pillar:UInt32 = 0b10// 2
static let Chest:UInt32 = 0b100// 4
static let Ladder:UInt32 = 0b1000
}
And the character physics is like this:
playerWalk.physicsBody?.categoryBitMask=PhysicsCategory.Player
playerWalk.physicsBody?.collisionBitMask=PhysicsCategory.Pillar
playerWalk.physicsBody?.contactTestBitMask=PhysicsCategory.Chest | PhysicsCategory.Ladder
playerWalk.physicsBody = SKPhysicsBody(rectangleOf:
playerWalk.frame.size)
For some reason the character stops at the ladder instead of moving on top of it. I can't figure out what I'm doing wrong.
Edit - You've set the properties of the playerWalk physics body before you've actually created the playerWalk.physicsBody. So the values for the categoryBitMask, collisionBitMask and contactTestBitMask don't get set because you've used optional chaining and so playerWalk.physicsBody? resolved to nil and nothing gets set.
Then, when you create the playerWalk physic body it just has the defaults properties i.e. no category, no contacts and collides with everything, so it is colliding with your ladder and thus cannot move over it.
Move the line:
playerWalk.physicsBody = SKPhysicsBody(rectangleOf: playerWalk.frame.size)
to before the lines where you set the physics body's properties.

Box2D: How to use b2ChainShape for a tile based map with squares

Im fighting here with the so called ghost collisions on a simple tile based map with a circle as player character.
When applying an impulse to the circle it first starts bouncing correctly, then sooner or later it bounces wrong (wrong angle).
Looking up on the internet i read about an issue in Box2D (i use iOS Swift with Box2d port for Swift).
Using b2ChainShape does not help, but it looks i misunderstood it. I also need to use the "prevVertex" and "nextVertex" properties to set up the ghost vertices.
But im confused. I have a simple map made up of boxes (simple square), all placed next to each other forming a closed room. Inside of it my circle i apply an impulse seeing the issue.
Now WHERE to place those ghost vertices for each square/box i placed on the view in order to solve this issue? Do i need to place ANY vertex close to the last and first vertice of chainShape or does it need to be one of the vertices of the next box to the current one? I dont understand. Box2D's manual does not explain where these ghost vertices coordinates are coming from.
Below you can see an image describing the problem.
Some code showing the physics parts for the walls and the circle:
First the wall part:
let bodyDef = b2BodyDef()
bodyDef.position = self.ptm_vec(node.position+self.offset)
let w = self.ptm(Constants.Config.wallsize)
let square = b2ChainShape()
var chains = [b2Vec2]()
chains.append(b2Vec2(-w/2,-w/2))
chains.append(b2Vec2(-w/2,w/2))
chains.append(b2Vec2(w/2,w/2))
chains.append(b2Vec2(w/2,-w/2))
square.createLoop(vertices: chains)
let fixtureDef = b2FixtureDef()
fixtureDef.shape = square
fixtureDef.filter.categoryBits = Constants.Config.PhysicsCategory.Wall
fixtureDef.filter.maskBits = Constants.Config.PhysicsCategory.Player
let wallBody = self.world.createBody(bodyDef)
wallBody.createFixture(fixtureDef)
The circle part:
let bodyDef = b2BodyDef()
bodyDef.type = b2BodyType.dynamicBody
bodyDef.position = self.ptm_vec(node.position+self.offset)
let circle = b2CircleShape()
circle.radius = self.ptm(Constants.Config.playersize)
let fixtureDef = b2FixtureDef()
fixtureDef.shape = circle
fixtureDef.density = 0.3
fixtureDef.friction = 0
fixtureDef.restitution = 1.0
fixtureDef.filter.categoryBits = Constants.Config.PhysicsCategory.Player
fixtureDef.filter.maskBits = Constants.Config.PhysicsCategory.Wall
let ballBody = self.world.createBody(bodyDef)
ballBody.linearDamping = 0
ballBody.angularDamping = 0
ballBody.createFixture(fixtureDef)
Not sure that I know of a simple solution in the case that each tile can potentially have different physics.
If your walls are all horizontal and/or vertical, you could write a class to take a row of boxes, create a single edge or rectangle body, and then on collision calculate which box (a simple a < x < b test) should interact with the colliding object, and apply the physics appropriately, manually calling the OnCollision method that you would otherwise specify as the callback for each individual box.
Alternatively, to avoid the trouble of manually testing intersection with different boxes, you could still merge all common straight edge boxes into one edge body for accurate reflections. However, you would still retain the bodies for the individual boxes. Extend the boxes so that they overlap the edge.
Now here's the trick: all box collision handlers return false, but they toggle flags on the colliding object (turning flags on OnCollision, and off OnSeparation). The OnCollision method for the edge body then processes the collision based on which flags are set.
Just make sure that the colliding body always passes through a box before it can touch an edge. That should be straightforward.

Magnetic field affects unwanted sprite

I have a Player Sprite which moves as the user drag their finger across the screen. I have implemented a power that the player sprite creates a magnetic repulsive force around it.
My dilemma is that when the power is turned on the player sprite itself gets affect my it when it shouldn't be.
I have set the correct fieldBitMask and categoryBitMask on the desired sprites and the field node but still doesn't work.
This is my players physicsBody configuration:
physics.affectedByGravity = false
physics.allowsRotation = false
physics.dynamic = true;
sprite.physicsBody?.fieldBitMask = 0
Set player node:
physics.dynamic = false

Resources