ARKit Physics Objects Phasing through tracked planes - physics

I am currently trying to modify the plane tracking demo that apple provided to have little cube projectiles bounce off the tracking planes that the app creates.
I have added physics bodies to the respective projectile and wall, but for some reason the projectile continues to ignore the collisions and just phases through the wall. I have tried adding and removing the bit masks, but they don't seem to affect anything.
Here is what I am currently doing for my tracked planes:
init (anchor: ARPlaneAnchor, in sceneView: ARSCNView) {
guard let meshGeometry = ARSCNPlaneGeometry(device: sceneView.device!) else {
fatalError("CANNOT CREATE GEOMETRY")
}
meshGeometry.update(from: anchor.geometry)
meshNode = SCNNode(geometry: meshGeometry)
meshNode.name = "ENV."
super.init()
self.setupMeshVisualStyle()
let body = SCNPhysicsBody(type: .static, shape: nil)
meshNode.physicsBody = body
addChildNode(meshNode)
}
Here is the bullet physics implementation
class func spawnBullet() -> SCNNode {
// Omitted code (just setting size and stuff)
let cubeNode = SCNNode(geometry: cubeGeometry)
cubeNode.name = "BULLET"
let physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.dynamic, shape: nil)
physicsBody.isAffectedByGravity = false
physicsBody.damping = 0
physicsBody.categoryBitMask = CollisionCategory.bullet.rawValue
physicsBody.collisionBitMask = CollisionCategory.env.rawValue | CollisionCategory.player.rawValue
physicsBody.continuousCollisionDetectionThreshold = 0.01;
cubeNode.physicsBody = physicsBody
return cubeNode
}
I have created a separate SCNPlane object with the exact same physics body settings as the tracked plane settings. What's odd is that the bullets successfully collide off of the SCNPlane, but they continue to pass through the tracked planes with the exact same settings.

Related

how to check for collisions in spritekit

this has probably already been answered but I can't find any examples. Is there an EFFECTIVE way to detect collisions in sprite kit between nodes. I already tried to detect between nodes with this code.
if ([leftArrow intersectsNode:gravitySquare])
{
//blah blah blah
}
else if ([rightArrow intersectsNode:gravitySquare])
{
//blah blah blah
}
and this works but my character "gravitySquare" can sometimes pass through the edges of right arrow and left arrow with having no results (I assume this is because of the speed the nodes are going at). Is there a way to implement physics bodies to detect collisions without them having any actual effect on each other I mean to still pass through each other.
edit:
I added these as fields in the implementation file
static const int gravitySqrCategory = 1;
static const int arrowsCategory = 2;
I added this to the gravity square node
gravitySquare.physicsBody.categoryBitMask = gravitySqrCategory;
gravitySquare.physicsBody.contactTestBitMask = arrowsCategory;
gravitySquare.physicsBody.collisionBitMask = arrowsCategory;
I added these to the two arrow nodes
leftArrow.physicsBody.categoryBitMask = arrowsCategory;
leftArrow.physicsBody.contactTestBitMask = gravitySqrCategory;
leftArrow.physicsBody.collisionBitMask = gravitySqrCategory;
rightArrow.physicsBody.categoryBitMask = arrowsCategory;
rightArrow.physicsBody.contactTestBitMask = gravitySqrCategory;
rightArrow.physicsBody.collisionBitMask = gravitySqrCategory;
and this is the did begin contact method
-(void)didBeginContact:(SKPhysicsContact *)contact
{
SKPhysicsBody *firstBody, *secondBody;
firstBody = contact.bodyA;
secondBody = contact.bodyB;
if(firstBody.categoryBitMask == arrowsCategory || secondBody.categoryBitMask == arrowsCategory)
{
NSLog(#"hit");
}
}
I also added this to the .h file
<SKPhysicsContactDelegate>
extra information:
I have arrows coming from the left and right which I move with skactions so I originally didn't need to have physics bodies for them I just had a physics body on the gravity square so it could fly up and down. but now that i add the physics body to the arrows it makes the square fly around in tangents without even touching the spikes and i rarely get that "hit" nslog when in contact.

Preventing SKSpriteNode from going off screen

I have a SKSpriteNode that moves with the accelerometer by using the following code:
-(void)processUserMotionForUpdate:(NSTimeInterval)currentTime {
SKSpriteNode* ship = (SKSpriteNode*)[self childNodeWithName:#"fishderp"];
CMAccelerometerData* data = self.motionManager.accelerometerData;
if (fabs(data.acceleration.y) > 0.2) {
[gameFish.physicsBody applyForce:CGVectorMake(0, data.acceleration.y)];
}
}
This works well however, the node (gamefish) moves off the screen. How can I prevent this and have it stay on the screen?
Try using an SKConstraint which was designed exactly for this purpose and introduced in iOS8:
Just add this to the setup method of the gameFish node. The game engine will apply the constraint after the physics has run. You won't have to worry about it. Cool huh?
// get the screensize
CGSize scr = self.scene.frame.size;
// setup a position constraint
SKConstraint *c = [SKConstraint
positionX:[SKRange rangeWithLowerLimit:0 upperLimit:scr.width]
Y:[SKRange rangeWithLowerLimit:0 upperLimit:scr.width]];
gameFish.constraints = #[c]; // can take an array of constraints
The code depends on whether you have added the gameFish node to self or to another node (something like a "worldNode"). If you have added it to self, look at the code below:
// get the screen height as you are only changing your node's y
float myHeight = self.view.frame.size.height;
// next check your node's y coordinate against the screen y range
// and adjust y if required
if(gameFish.position.y > myHeight) {
gameFish.position = CGPointMake(gameFish.position.x, myHeight);
}
For the bottom you can do a check of < 0 or whatever value you need.

Add boundaries to an SKScene

I'm trying to write a basic game using Apple's Sprite Kit framework. So far, I have a ship flying around the screen, using SKPhysicsBody. I want to keep the ship from flying off the screen, so I edited my update method to make the ship's velocity zero. This works most of the time, but every now and then, the ship will fly off the screen.
Here's my update method.
// const int X_MIN = 60;
// const int X_MAX = 853;
// const int Y_MAX = 660;
// const int Y_MIN = 60;
// const float SHIP_SPEED = 50.0;
- (void)update:(CFTimeInterval)currentTime {
if (self.keysPressed & DOWN_ARROW_PRESSED) {
if (self.ship.position.y > Y_MIN) {
[self.ship.physicsBody applyForce:CGVectorMake(0, -SHIP_SPEED)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(self.ship.physicsBody.velocity.dx, 0);
}
}
if (self.keysPressed & UP_ARROW_PRESSED) {
if (self.ship.position.y < Y_MAX) {
[self.ship.physicsBody applyForce:CGVectorMake(0, SHIP_SPEED)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(self.ship.physicsBody.velocity.dx, 0);
}
}
if (self.keysPressed & RIGHT_ARROW_PRESSED) {
if (self.ship.position.x < X_MAX) {
[self.ship.physicsBody applyForce:CGVectorMake(SHIP_SPEED, 0)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(0, self.ship.physicsBody.velocity.dy);
}
}
if (self.keysPressed & LEFT_ARROW_PRESSED) {
if (self.ship.position.x > X_MIN) {
[self.ship.physicsBody applyForce:CGVectorMake(-SHIP_SPEED, 0)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(0, self.ship.physicsBody.velocity.dy);
}
}
}
At first, I used applyImpulse in didBeginContact to push the ship back. This made the ship bounce, but I don't want the ship to bounce. I just want it to stop at the edge.
What is the right way to make the ship stop once it reaches the edge? The code above works most of the time, but every now and then the ship shoots off screen. This is for OS X—not iOS—in case that matters.
Check out this link...
iOS7 SKScene how to make a sprite bounce off the edge of the screen?
[self setPhysicsBody:[SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame]]; //Physics body of Scene
This should set up a barrier around the edge of your scene.
EDIT:
This example project from Apple might also be useful
https://developer.apple.com/library/mac/samplecode/SpriteKit_Physics_Collisions/Introduction/Intro.html
Your code is not clear in what the velocity variables represent. Keep in mind that if the velocity is too high your ship will have travelled multiple points between updates. For example, your ship's X/Y is at (500,500) at the current update. Given a high enough velocity, your ship could be at (500,700) at the very next update. If you had your boundary set at (500,650) your ship would already be past it.
I suggest you do a max check on velocity BEFORE applying it to your ship. This should avoid the problem I outlined above.
As for bouncy, bouncy... did you try setting your ship's self.physicsBody.restitution = 0; ? The restitution is the bounciness of the physics body. If you use your own screen boundaries, then I would recommend setting those to restitution = 0 as well.
Your best bet would be to add a rectangle physics body around the screen (boundary). Set the collision and contact categories of the boundary and player to interact with each other. In the didBeginContact method you can check if the bodies have touched and, if they have, you can call a method to redirect the ship.
Your problem is that your update method may not be checking the location frequently enough before the ship gets off screen.
This will help you to define you screen edges in Swift.
self.physicsBody = SKPhysicsBody ( edgeLoopFromRect: self.frame )

SpriteKit: How to simulate magnetic force

I am developing a game using iOS SpriteKit. I am trying to make an object in this game that will pull things towards it and the force will get greater as objects come closer to it, think of a magnet or a black hole. I've been having a difficult time figuring out what properties to change to get this nodes physicsBody to attract other nodes as they pass by.
In iOS 8 and OS X 10.10, SpriteKit has SKFieldNode for creating forces that apply to bodies in an area. This is great for things like buoyancy, area-specific gravity, and "magnets".
Watch out, though — the magneticField you get from that class is probably not what you want for the kind of "magnets" gameplay you might be looking for. A magnetic field behaves as per real-world physics at the micro level... that is, it deflects moving, charged bodies. What we usually think of as magnets — the kind that stick to your fridge, pick up junked cars, or make a hoverboard fly — is a higher-level effect of that force.
If you want a field that just attracts anything (or some specific things) nearby, a radialGravityField is what you're really after. (To attract only specific things, use the categoryBitMask on the field and the fieldBitMask on the bodies it should/shouldn't interact with.)
If you want a field that attracts different things more or less strongly, or attracts some things and repels others, the electricField is a good choice. You can use the charge property of physics bodies to make them attracted or repelled (negative or positive values) or more or less strongly affected (greater or less absolute value) by the field.
Prior to iOS 8 & OS X 10.10, SpriteKit's physics simulation doesn't include such kinds of force.
That doesn't keep you from simulating it yourself, though. In your scene's update: method you can find the distances between bodies, calculate a force on each proportional to that distance (and to whatever strength of magnetic field you're simulating), and apply forces to each body.
yes you can create magnetic force in sprite kit
-(void)didSimulatePhysics
{
[self updateCoin];
}
-(void) updateCoin
{
[self enumerateChildNodesWithName:#"coin" usingBlock:^(SKNode *node, BOOL *stop) {
CGPoint position;
position=node.position;
//move coin right to left
position.x -= 10;
node.position = position;
//apply the magnetic force between hero and coin
[self applyMagnetForce:coin];
if (node.position.x <- 100)
[node removeFromParent];
}];
}
-(void)applyMagnetForce:(sprite*)node
{
if( gameViewController.globalStoreClass.magnetStatus)
{
//if hero under area of magnetic force
if(node.position.x<400)
{
node.physicsBody.allowsRotation=FALSE;
///just for fun
node.physicsBody.linearDamping=10;
node.physicsBody.angularVelocity=10*10;
//where _gameHero is magnet fulling object
[node.physicsBody applyForce:CGVectorMake((10*10)*(_gameHero.position.x- node.position.x),(10*10)*(_gameHero.position.y-node.position.y)) atPoint:CGPointMake(_gameHero.position.x,_gameHero.position.y)];
}
}
}
remember both hero and coin body need be dynamic
Well seems like now you can since Apple introduced SKFieldNode in iOS 8.
Well you use the following code snippets to do what you're looking for, but it doesn't have attraction and repulsion properties
Body code:
let node = SKSpriteNode(imageNamed: "vortex")
node.name = "vortex"
node.position = position
node.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat.pi, duration: 1)))
node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
node.physicsBody?.isDynamic = false
node.physicsBody?.categoryBitMask = CollisionTypes.vortex.rawValue
node.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
node.physicsBody?.collisionBitMask = 0
addChild(node)
Upon contact with the that blackhole body:
func playerCollided(with node: SKNode) {
if node.name == "vortex" {
player.physicsBody?.isDynamic = false
isGameOver = true
score -= 1
let move = SKAction.move(to: node.position, duration: 0.25)
let scale = SKAction.scale(to: 0.0001, duration: 0.25)
let remove = SKAction.removeFromParent()
let sequence = SKAction.sequence([move, scale, remove])
player.run(sequence) { [unowned self] in
self.createPlayer()
self.isGameOver = false
}
}

Unity3D - Top Down Camera Logic Gets Locked When Using Transform.LookAt

I've put together a custom top-down camera logic script based on Unity3D's ThirdPersonCamera.js script. Everything appears to be working properly, the camera follows the target player on the XZ plane and even moves along the Y-axis as appropriate when the player jumps.
Only the camera isn't looking at the player. So I tried using Transform.LookAt() on the cameraTransform to have the camera looking directly down on the player. This does cause the camera to correctly look directly down on the player, but then movement via WASD no longer works. The player just sits there. Using Spacebar for jumping does still work though.
This doesn't make sense to me, how should the orientation of the camera's transform be affecting the movement of the player object?
The code for my script is below:
// The transform of the camera that we're manipulating
var cameraTransform : Transform;
// The postion that the camera is currently focused on
var focusPosition = Vector3.zero;
// The idle height we are aiming to be above the target when the target isn't moving
var idleHeight = 7.0;
// How long should it take the camera to focus on the target on the XZ plane
var xzSmoothLag = 0.3;
// How long should it take the camera to focus on the target vertically
var heightSmoothLag = 0.3;
private var _target : Transform;
private var _controller : ThirdPersonController;
private var _centerOffset = Vector3.zero;
private var _headOffset = Vector3.zero;
private var _footOffset = Vector3.zero;
private var _xzVelocity = 0.0;
private var _yVelocity = 0.0;
private var _cameraHeightVelocity = 0.0;
// ===== UTILITY FUNCTIONS =====
// Apply the camera logic to the camera with respect for the target
function process()
{
// Early out if we don't have a target
if ( !_controller )
return;
var targetCenter = _target.position + _centerOffset;
var targetHead = _target.position + _headOffset;
var targetFoot = _target.position + _footOffset;
// Determine the XZ offset of the focus position from the target foot
var xzOffset = Vector2(focusPosition.x, focusPosition.z) - Vector2(targetFoot.x, targetFoot.z);
// Determine the distance of the XZ offset
var xzDistance = xzOffset.magnitude;
// Determine the Y distance of the focus position from the target foot
var yDistance = focusPosition.y - targetFoot.y;
// Damp the XZ distance
xzDistance = Mathf.SmoothDamp(xzDistance, 0.0, _xzVelocity, xzSmoothLag);
// Damp the XZ offset
xzOffset *= xzDistance;
// Damp the Y distance
yDistance = Mathf.SmoothDamp(yDistance, 0.0, _yVelocity, heightSmoothLag);
// Reposition the focus position by the dampened distances
focusPosition.x = targetFoot.x + xzOffset.x;
focusPosition.y = targetFoot.y + yDistance;
focusPosition.z = targetFoot.z + xzOffset.y;
var minCameraHeight = targetHead.y;
var targetCameraHeight = minCameraHeight + idleHeight;
// Determine the current camera height with respect to the minimum camera height
var currentCameraHeight = Mathf.Max(cameraTransform.position.y, minCameraHeight);
// Damp the camera height
currentCameraHeight = Mathf.SmoothDamp( currentCameraHeight, targetCameraHeight, _cameraHeightVelocity, heightSmoothLag );
// Position the camera over the focus position
cameraTransform.position = focusPosition;
cameraTransform.position.y = currentCameraHeight;
// PROBLEM CODE - BEGIN
// Have the camera look at the focus position
cameraTransform.LookAt(focusPosition, Vector3.forward);
// PROBLEM CODE - END
Debug.Log("Camera Focus Position: " + focusPosition);
Debug.Log("Camera Transform Position: " + cameraTransform.position);
}
// ===== END UTILITY FUNCTIONS =====
// ===== UNITY FUNCTIONS =====
// Initialize the script
function Awake( )
{
// If the camera transform is unassigned and we have a main camera,
// set the camera transform to the main camera's transform
if ( !cameraTransform && Camera.main )
cameraTransform = Camera.main.transform;
// If we don't have a camera transform, report an error
if ( !cameraTransform )
{
Debug.Log( "Please assign a camera to the TopDownThirdPersonCamera script." );
enabled = false;
}
// Set the target to the game object transform
_target = transform;
// If we have a target set the controller to the target's third person controller
if ( _target )
{
_controller = _target.GetComponent( ThirdPersonController );
}
// If we have a controller, calculate the center offset and head offset
if ( _controller )
{
var characterController : CharacterController = _target.collider;
_centerOffset = characterController.bounds.center - _target.position;
_headOffset = _centerOffset;
_headOffset.y = characterController.bounds.max.y - _target.position.y;
_footOffset = _centerOffset;
_footOffset.y = characterController.bounds.min.y - _target.position.y;
}
// If we don't have a controller, report an error
else
Debug.Log( "Please assign a target to the camera that has a ThirdPersonController script attached." );
// Apply the camera logic to the camera
process();
}
function LateUpdate( )
{
// Apply the camera logic to the camera
process();
}
// ===== END UNITY FUNCTIONS =====
I've marked the problem code section with PROBLEM CODE comments. If the problem code is removed, it allows WASD movement to work again, but then the camera is no longer looking at the target.
Any insight into this issue is very much appreciated.
I figured it out, the issue was with the ThirdPersonController.js script that I was using. In the function UpdateSmoothedMovementDirection(), the ThirdPersonController uses the cameraTransform to determine the forward direction along the XZ plane based on where the camera is looking at. In doing so, it zeros out the Y axis and normalizes what's left.
The cameraTransform.LookAt() call I perform in my custom TopDownCamera.js script has the camera looking directly down the Y-axis. So when the ThirdPersonController gets a hold of it and zeros out the Y-axis, I end up with zero forward direction, which causes the XZ movement to go nowhere.
Copying ThirdPersonController.js and altering the code so that:
var forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
becomes:
forward = Vector3.forward;
fixed the issue.