I am having trouble figuring out how to differentiate between different bitmasks.
I want this to happen:
/*func didBegin(_ contact: SKPhysicsContact) {
if (spaceship1 collides with spaceship2) {
print("contact between 1 and 2")
}
if (spaceship1 collides with spaceship3) {
print("contact between 1 and 3")
}
}
*/
Here's the code I have tried:
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask = enemyCategory && contact.bodyB.categoryBitMask = enemy2Category) {
print("contact between 1 and 2")
}
}
Could I get some help?
EDIT: Here's the other code:
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let enemy2Category: UInt32 = 1
let enemyCategory: UInt32 = 2
let enemy3Category: UInt32 = 3
var spaceship1: SKSpriteNode!
var spaceship2: SKSpriteNode!
var spaceship3: SKSpriteNode!
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
spaceship1 = SKSpriteNode(imageNamed: "Spaceship");
spaceship1.setScale(CGFloat(0.1))
spaceship1.position = CGPoint(x: self.frame.width / 2, y: (self.frame.height / 2));
spaceship1.name = "spaceship1";
spaceship1.physicsBody = SKPhysicsBody(circleOfRadius: spaceship1.size.width / 2);
spaceship1.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship1.physicsBody?.affectedByGravity = true;
spaceship1.physicsBody?.allowsRotation = false
spaceship1.physicsBody = SKPhysicsBody(circleOfRadius: spaceship1.size.width / 2);
spaceship1.physicsBody?.categoryBitMask = enemy2Category
spaceship1.physicsBody?.collisionBitMask = enemyCategory
spaceship1.physicsBody?.contactTestBitMask = enemyCategory
spaceship2 = SKSpriteNode(imageNamed: "Spaceship");
spaceship2.setScale(CGFloat(0.1))
spaceship2.position = CGPoint(x: self.frame.width / 2, y: (spaceship1.position.y + 300));
spaceship2.name = "spaceship2";
spaceship2.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship2.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship2.physicsBody?.affectedByGravity = false;
spaceship2.physicsBody?.allowsRotation = false
spaceship2.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship2.physicsBody?.categoryBitMask = enemyCategory
spaceship2.physicsBody?.collisionBitMask = enemy2Category
spaceship2.physicsBody?.contactTestBitMask = enemy2Category
spaceship3 = SKSpriteNode(imageNamed: "Spaceship");
spaceship3.setScale(CGFloat(0.1))
spaceship3.position = CGPoint(x: self.frame.width / 2, y: (spaceship1.position.y + 300));
spaceship3.name = "spaceship3";
spaceship3.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship3.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship3.physicsBody?.affectedByGravity = false;
spaceship3.physicsBody?.allowsRotation = false
spaceship3.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship3.physicsBody?.categoryBitMask = enemy3Category
spaceship3.physicsBody?.collisionBitMask = enemy2Category | enemyCategory
spaceship3.physicsBody?.contactTestBitMask = enemy2Category | enemyCategory
addChild(spaceship1)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
addChild(spaceship3)
}
override func update(_ currentTime: TimeInterval) {
spaceship1.physicsBody?.affectedByGravity = false;
}
}
I'm just trying to figure out how to detect which bitmasks come into contact with each other. Like if spaceship1 comes into contact with spaceship2, it prints yay, but if spaceship1 comes into contact with spaceship 3, it prints "wow"
There is a documentation article that tries to explain bit masks as used in Sprite-Kit collision and contacts, but I can no longer link to it. Try to find the 'Documentation' page, tag 'Sprite-Kit' then the 'Manipulating contactTest and collison bitmasks to enable/disable specific contact and collisions.' article under 'SKNode Collision'.
One obvious problem is this line :
let enemy3Category: UInt32 = 3
All bitmasks have to be thought of in binary, and in binary 3 is 11. This is the '1' bit and the '2' bit both being set to 1. Category definitions should only have 1 bit set to 1 which you ensure by using exact powers of 2 for your categories - 1, 2, 4, 8, 16, 32, etc.
Objects in your scene that need to collide/contact should belong to only one category initially. For more advanced contacts and collisions, a sprite can belong to multiple categories.
You are missing an = in your if statement.
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == enemyCategory && contact.bodyB.categoryBitMask == enemy2Category) {
print("contact between 1 and 2")
}
}
This sets firstBody to the smaller bitmask And sets secondBody to the larger one
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
}else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
Assuiming bitmask1 is smaller than 2 and 3.
if firstBody.categoryBitMask == bitMask1 && secondBody.categoryBitMask == bitMask.bitmask3 {
print("a")
//If ball hits a pad, activate the pad
}else if firstBody.categoryBitMask == bitMask1 && secondBody.categoryBitMask == bitMask.bitmask2 {
print("e")
}
Related
I try to make an endless background through the nodes, but the background has not become infinite and is interrupted, the third background is not yet shown. After the first show, the number of nodes in the scene grows, how can this be fixed?
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var bgNode: SKNode!
var overlay: SKNode!
var overlayWidth: CGFloat!
//var viewSize: CGSize!
var levelPositionX: CGFloat = 0.0
//var speed: CGFloat = 5.5
override func didMove(to view: SKView) {
setupNode()
//viewSize = CGSize(width: frame.size.width, height:
frame.size.height )
}
func setupNode() {
let worldNode = childNode(withName: "World")!
bgNode = worldNode.childNode(withName: "Background")!
overlay = bgNode.childNode(withName: "Overlay")!.copy() as!
SKNode
overlayWidth = overlay.calculateAccumulatedFrame().width
}
func createBackgroundOverlay() {
let backgroundOverlay = overlay.copy() as! SKNode
backgroundOverlay.position = CGPoint(x: 0.0, y: 0.0)
bgNode.addChild(backgroundOverlay)
levelPositionX += overlayWidth
}
func update() {
bgNode.position.x -= 5
if bgNode.position.x <= -self.frame.size.width {
bgNode.position.x = self.frame.size.width * 2
createBackgroundOverlay()
}
}
override func update(_ currentTime: TimeInterval) {
update()
}
In my endless runner game, I have implemented an endless background and a ground(or floor) much similar to your app. Below I shall discuss the steps i have used in my game.
Step 1: In your GameScene.swift file add these variables.
var backgroundSpeed: CGFloat = 80.0 // speed may vary as you like
var deltaTime: TimeInterval = 0
var lastUpdateTimeInterval: TimeInterval = 0
Step 2: In GameScene file, make setUpBackgrouds method as follows
func setUpBackgrounds() {
//add background
for i in 0..<3 {
// add backgrounds, my images were namely, bg-0.png, bg-1.png, bg-2.png
let background = SKSpriteNode(imageNamed: "bg-\(i).png")
background.anchorPoint = CGPoint.zero
background.position = CGPoint(x: CGFloat(i) * size.width, y: 0.0)
background.size = self.size
background.zPosition = -5
background.name = "Background"
self.addChild(background)
}
for i in 0..<3 {
// I have used one ground image, you can use 3
let ground = SKSpriteNode(imageNamed: "Screen.png")
ground.anchorPoint = CGPoint(x: 0, y: 0)
ground.size = CGSize(width: self.size.width, height: ground.size.height)
ground.position = CGPoint(x: CGFloat(i) * size.width, y: 0)
ground.zPosition = 1
ground.name = "ground"
self.addChild(ground)
}
}
Step 3: Now we have to capture timeIntervals from update method
override func update(_ currentTime: TimeInterval) {
if lastUpdateTimeInterval == 0 {
lastUpdateTimeInterval = currentTime
}
deltaTime = currentTime - lastUpdateTimeInterval
lastUpdateTimeInterval = currentTime
}
Step 4: Here comes the most important part, moving our backgrounds and groungFloor by enumerating child nodes. Add these two methods in GameScene.swift file.
func updateBackground() {
self.enumerateChildNodes(withName: "Background") { (node, stop) in
if let back = node as? SKSpriteNode {
let move = CGPoint(x: -self.backgroundSpeed * CGFloat(self.deltaTime), y: 0)
back.position += move
if back.position.x < -back.size.width {
back.position += CGPoint(x: back.size.width * CGFloat(3), y: 0)
}
}
}
}
func updateGroundMovement() {
self.enumerateChildNodes(withName: "ground") { (node, stop) in
if let back = node as? SKSpriteNode {
let move = CGPoint(x: -self.backgroundSpeed * CGFloat(self.deltaTime), y: 0)
back.position += move
if back.position.x < -back.size.width {
back.position += CGPoint(x: back.size.width * CGFloat(3), y: 0)
}
}
}
}
Step 5: At this point you should get this error:"Binary operator '+=' cannot be applied to two 'CGPoint' operands" in updateBackground and updateGroundMovement methods.
Now we need to implement operator overloading to resolve this problem. Create a new Swift File and name it Extensions.swift and then implement as follows:
// Extensions.swift
import CoreGraphics
import SpriteKit
public func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
public func += (left: inout CGPoint, right: CGPoint) {
left = left + right
}
Step 6: call setUpBackgrounds method in didMove(toView:)
override func didMove(to view: SKView) {
setUpBackgrounds()
}
Step 7: Finally call the updateBackground and updateGroundMovement methods in update(_ currentTime) method. updated code is given below:
override func update(_ currentTime: TimeInterval) {
if lastUpdateTimeInterval == 0 {
lastUpdateTimeInterval = currentTime
}
deltaTime = currentTime - lastUpdateTimeInterval
lastUpdateTimeInterval = currentTime
//MARK:- Last step:- add these methods here
updateBackground()
updateGroundMovement()
}
I'm new to swift and I have been trying to figure out how to use bitmasks and didBegin(_ contact: SKPhysicsContact) to detect when two spaceships touch each other. I can't seem to figure out how.
Here is what I have so far:
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let pufferCategory: UInt32 = 1 << 0;
let enemyCategory: UInt32 = 1 << 1;
var spaceship1: SKSpriteNode!
var spaceship2: SKSpriteNode!
override func didMove(to view: SKView) {
spaceship1 = SKSpriteNode(imageNamed: "Spaceship");
spaceship1.setScale(CGFloat(0.1))
spaceship1.position = CGPoint(x: self.frame.width / 2, y: (self.frame.height / 2));
spaceship1.name = "spaceship1";
spaceship1.physicsBody = SKPhysicsBody(circleOfRadius: spaceship1.size.width / 2);
spaceship1.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship1.physicsBody?.affectedByGravity = false;
spaceship1.physicsBody?.allowsRotation = false
spaceship1.physicsBody = SKPhysicsBody(circleOfRadius: spaceship1.size.width / 2);
spaceship1.physicsBody?.categoryBitMask = pufferCategory
spaceship1.physicsBody?.contactTestBitMask = enemyCategory
spaceship2 = SKSpriteNode(imageNamed: "Spaceship");
spaceship2.setScale(CGFloat(0.1))
spaceship2.position = CGPoint(x: self.frame.width / 2, y: (spaceship1.position.y + 300));
spaceship2.name = "puffer2";
spaceship2.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship2.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship2.physicsBody?.affectedByGravity = false;
spaceship2.physicsBody?.allowsRotation = false
spaceship2.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship2.physicsBody?.categoryBitMask = enemyCategory
spaceship2.physicsBody?.contactTestBitMask = pufferCategory
addChild(spaceship1)
addChild(spaceship2)
}
func didBegin(_ contact: SKPhysicsContact) {
print("contact")
}
override func update(_ currentTime: TimeInterval) {
spaceship1.physicsBody?.affectedByGravity = false;
}
}
Thanks in advance!
I figured it out!
Here's my code :)
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let enemy2Category: UInt32 = 1
let enemyCategory: UInt32 = 2
var spaceship1: SKSpriteNode!
var spaceship2: SKSpriteNode!
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
spaceship1 = SKSpriteNode(imageNamed: "Spaceship");
spaceship1.setScale(CGFloat(0.1))
spaceship1.position = CGPoint(x: self.frame.width / 2, y: (self.frame.height / 2));
spaceship1.name = "spaceship1";
spaceship1.physicsBody = SKPhysicsBody(circleOfRadius: spaceship1.size.width / 2);
spaceship1.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship1.physicsBody?.affectedByGravity = false;
spaceship1.physicsBody?.allowsRotation = false
spaceship1.physicsBody = SKPhysicsBody(circleOfRadius: spaceship1.size.width / 2);
spaceship1.physicsBody?.categoryBitMask = enemy2Category
spaceship1.physicsBody?.collisionBitMask = enemyCategory
spaceship1.physicsBody?.contactTestBitMask = enemyCategory
spaceship2 = SKSpriteNode(imageNamed: "Spaceship");
spaceship2.setScale(CGFloat(0.1))
spaceship2.position = CGPoint(x: self.frame.width / 2, y: (spaceship1.position.y + 300));
spaceship2.name = "spaceship2";
spaceship2.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship2.physicsBody?.isDynamic = true // apply gravity, friction, and collision
spaceship2.physicsBody?.affectedByGravity = false;
spaceship2.physicsBody?.allowsRotation = false
spaceship2.physicsBody = SKPhysicsBody(circleOfRadius: spaceship2.size.width / 2);
spaceship2.physicsBody?.categoryBitMask = enemyCategory
spaceship2.physicsBody?.collisionBitMask = enemy2Category
spaceship2.physicsBody?.contactTestBitMask = enemy2Category
addChild(spaceship1)
addChild(spaceship2)
}
func didBegin(_ contact: SKPhysicsContact) {
print("contact")
}
override func update(_ currentTime: TimeInterval) {
spaceship1.physicsBody?.affectedByGravity = false;
}
}
I used this video to help: https://www.youtube.com/watch?v=43hzb4NmQfw
I'm trying to solving a problem where a sprite node can jump up through a platform but cannot jump back down. I tried using this code:
override func didMove(to view: SKView) {
if (thePlayer.position.y > stonePlatform1.position.y) == true {
stonePlatform1.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: stonePlatform.size.width * 0.9, height: stonePlatform.size.height * 0.75))
stonePlatform1.physicsBody!.isDynamic = false
stonePlatform1.physicsBody!.affectedByGravity = false
stonePlatform1.physicsBody!.categoryBitMask = BodyType.object.rawValue
stonePlatform1.physicsBody!.contactTestBitMask = BodyType.object.rawValue
stonePlatform1.physicsBody!.restitution = 0.4
}
}
The idea was to turn on the physics body of the platform on when the player is above the platform. However, the physics doesn't work at all when I use this code. In fact I tried using this code:
override func didMove(to view: SKView) {
if (thePlayer.position.y < stonePlatform1.position.y) == true {
stonePlatform1.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: stonePlatform.size.width * 0.9, height: stonePlatform.size.height * 0.75))
stonePlatform1.physicsBody!.isDynamic = false
stonePlatform1.physicsBody!.affectedByGravity = false
stonePlatform1.physicsBody!.categoryBitMask = BodyType.object.rawValue
stonePlatform1.physicsBody!.contactTestBitMask = BodyType.object.rawValue
stonePlatform1.physicsBody!.restitution = 0.4
}
}
and the physics doesn't turn on either. If the IF statement isn't there, the physics does work all of the time.
You can use the node velocity for this platforms, like this:
SpriteKit - Swift 3 code:
private var up1 : SKSpriteNode!
private var down1 : SKSpriteNode!
private var down2 : SKSpriteNode!
private var player : SKSpriteNode!
override func didMove(to view: SKView) {
up1 = self.childNode(withName: "up1") as! SKSpriteNode
down1 = self.childNode(withName: "down1") as! SKSpriteNode
down2 = self.childNode(withName: "down2") as! SKSpriteNode
player = self.childNode(withName: "player") as! SKSpriteNode
up1.physicsBody?.categoryBitMask = 0b0001 // Mask for UoPlatforms
down1.physicsBody?.categoryBitMask = 0b0010 // Mask for downPlatforms
down2.physicsBody?.categoryBitMask = 0b0010 // Same mask
}
override func update(_ currentTime: TimeInterval) {
player.physicsBody?.collisionBitMask = 0b0000 // Reset the mask
// For UP only Platform
if (player.physicsBody?.velocity.dy)! < CGFloat(0.0) {
player.physicsBody?.collisionBitMask |= 0b0001 // The pipe | operator adds the mask by binary operations
}
// For Down only platforms
if (player.physicsBody?.velocity.dy)! > CGFloat(0.0) {
player.physicsBody?.collisionBitMask |= 0b0010 // The pipe | operator adds the mask by binary operations
}
}
Source code with example here: https://github.com/Maetschl/SpriteKitExamples/tree/master/PlatformTest
The example show this:
Green platforms -> Down Only
Red platforms -> Up only
You could try just starting with the physics body as nil and then set the physics values to it after the player is above it. Also, this kind of code should be in the update function. Having it in didMove only lets it get called once.
override func update(_ currentTime: TimeInterval){
if (thePlayer.position.y < stonePlatform1.position.y) && stonePlatform1.physicsBody != nil {
stonePlatform1.physicsBody = nil
}else if (thePlayer.position.y > stonePlatform1.position.y) && stonePlatform1.physicsBody == nil{
setPhysicsOnPlatform(stonePlatform1)
}
}
func setPhysicsOnPlatform(_ platform: SKSpriteNode){
platform.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: stonePlatform.size.width * 0.9, height: stonePlatform.size.height * 0.75))
...
//the rest of your physics settings
}
You should also do some handling for the height of the player and your anchorPoint. Otherwise if your anchorPoint is (0,0) and the player is halfway through the platform, the physics will be applied and a undesirable result will occur.
how do we create a UICollectionViewLayout like the SnapChat's stories?
Any ideas please?
I'd like to have a solution without external library.
Based on a precedent answer adapted to your issue:
-(id)initWithSize:(CGSize)size
{
self = [super init];
if (self)
{
_unitSize = CGSizeMake(size.width/2,80);
_cellLayouts = [[NSMutableDictionary alloc] init];
}
return self;
}
-(void)prepareLayout
{
for (NSInteger aSection = 0; aSection < [[self collectionView] numberOfSections]; aSection++)
{
//Create Cells Frames
for (NSInteger aRow = 0; aRow < [[self collectionView] numberOfItemsInSection:aSection]; aRow++)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:aRow inSection:aSection];
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
NSUInteger i = aRow%3;
NSUInteger j = aRow/3;
CGFloat offsetY = _unitSize.height*2*j;
CGPoint xPoint;
CGFloat height = 0;
BOOL invert = NO;
if (aRow%6 >= 3) //We need to invert Big cell and small cells => xPoint.x
{
invert = YES;
}
switch (i)
{
case 0:
xPoint = CGPointMake((invert?_unitSize.width:0), offsetY);
height = _unitSize.height;
break;
case 1:
xPoint = CGPointMake((invert?_unitSize.width:0), offsetY+_unitSize.height);
height = _unitSize.height;
break;
case 2:
xPoint = CGPointMake((invert?0:_unitSize.width), offsetY);
height = _unitSize.height*2;
break;
default:
break;
}
CGRect frame = CGRectMake(xPoint.x, xPoint.y, _unitSize.width, height);
[attributes setFrame:frame];
[_cellLayouts setObject:attributes forKey:indexPath];
}
}
}
I set the height of unitSize to 80, but you can use the size of the screen if needed, like _unitSize = CGSizeMake(size.width/2,size.height/4.);.
That render:
Side note: It's up to you to adapt the logic, or do changes, the cell frames calculation may not be the "best looking piece of code".
UICollectionViewLayout like the SnapChat's stories Like
Swift 3.2 Code
import Foundation
import UIKit
class StoryTwoColumnsLayout : UICollectionViewLayout {
fileprivate var cache = [IndexPath: UICollectionViewLayoutAttributes]()
fileprivate var cellPadding: CGFloat = 4
fileprivate var contentHeight: CGFloat = 0
var oldBound: CGRect!
let numberOfColumns:Int = 2
var cellHeight:CGFloat = 255
fileprivate var contentWidth: CGFloat {
guard let collectionView = collectionView else {
return 0
}
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override func prepare() {
super.prepare()
contentHeight = 0
cache.removeAll(keepingCapacity: true)
guard cache.isEmpty == true, let collectionView = collectionView else {
return
}
if collectionView.numberOfSections == 0 {
return
}
let cellWidth = contentWidth / CGFloat(numberOfColumns)
cellHeight = cellWidth / 720 * 1220
var xOffset = [CGFloat]()
for column in 0 ..< numberOfColumns {
xOffset.append(CGFloat(column) * cellWidth)
}
var column = 0
var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
var newheight = cellHeight
if column == 0 {
newheight = ((yOffset[column + 1] - yOffset[column]) > cellHeight * 0.3) ? cellHeight : (cellHeight * 0.90)
}
let frame = CGRect(x: xOffset[column], y: yOffset[column], width: cellWidth, height: newheight)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache[indexPath] = (attributes)
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] + newheight
if column >= (numberOfColumns - 1) {
column = 0
} else {
column = column + 1
}
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
// Loop through the cache and look for items in the rect
visibleLayoutAttributes = cache.values.filter({ (attributes) -> Bool in
return attributes.frame.intersects(rect)
})
print(visibleLayoutAttributes)
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
// print(cache[indexPath.item])
return cache[indexPath]
}
}
I have one object that collides with two other objects. I change restitution based on the collided objects in question. Whenever the restitution changes from 0.5 to 0 it isn't recognized immediately, this causes bounciness for a short while when the restitution is suppose to be zero. How can I make the change recognizable/effected immediately? Please see my code below:
func didBegin(_ contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody
var secondBody : SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == spriteCategory && secondBody.categoryBitMask == enemyCategory1 {
var spriteContactNode = firstBody.node
spriteContactNode?.physicsBody?.restitution = 0.5
self.physicsWorld.gravity = CGVector(dx: 0, dy: -2.0)
}
if firstBody.categoryBitMask == spriteCategory && secondBody.categoryBitMask == enemyCategory2 {
var spriteContactNode = firstBody.node
spriteContactNode?.physicsBody?.restitution = 0
self.physicsWorld.gravity = CGVector(dx: 0, dy: -0.5)
}
}
I don't believe what you're trying to do will work. Restitution affects a period of time, like if the node had an action that was repeated a few times.
Try changing the nodes isDynamic property to false instead.
var spriteContactNode = firstBody.node
spriteContactNode?.physicsBody?.isDynamic = false
spriteContactNode?.physicsBody?.restitution = 0
self.physicsWorld.gravity = CGVector(dx: 0, dy: -0.5)
spriteContactNode?.physicsBody?.isDynamic = true
Then setting it back to true may be enough to let bounce only once before falling with the gravity.