Detecting when a circle really intersects a node - ios

I use ball.frame.intersects(bar.frame), where ball = SKShapeNode(circleOfRadius: BALL_RADIUS) and bar = SKShapeNode(rectOfSize: <Some CGSize object>)
While this works, there is an invisible square in which the circle is inscribed. The diameter of the circle is the same as the side of the square. This square is what ball.frame is, so sometimes, the ball will act like it's intersecting the bar, but visually it's not.
In this screenshot you can see that the ball is stopped, and therefore the game is over because ball.frame.intersects(bar.frame) returned true, even though visually the ball isn't even touching the bar.
So how do I check if the ball is really intersecting the bar, and not if the ball's frame is intersecting?

SpriteKit has decently powerful collision detection in its physics subsystem — you don't have to roll your own.
Create SKPhysicsBody objects for the ball and the bars, using init(circleOfRadius:) for the former and init(rectangleOfSize: for the latter.
Then, you can either:
Drive all the movement yourself, and use SKPhysics only to test for collisions. In this case you need to set your scene's physicsWorld.gravity to the zero vector, and call allContactedBodies() on the ball when you want to see if it's contacting a bar.
Let SKPhysics drive the movement, by setting velocities or applying impulses. In this case you'll need to set a contact delegate for your physics world, and then you'll get a callback whenever a collision occurs.
For more details on either approach, see the docs.

After detecting that ball frame intersects box frame:
Determine the radius of the ball
Determine the point on the line that is the edge of the ball from the center of the ball to the edge of the box. (Hint: pythagorean theorem - hypotenuse = radius)
Is this point inside the box's rect?
Repeat for each point in the box.

Related

Notice when node position enters certain bounding box in scene kit?

is there a way to trigger a function, when a node (e.g. a tossed ball) enters a certain bounding box (e.g. a basket) in SceneKit / ARKit? If not, how would you implement this problem?
The way I would probably approach this. After obtaining a basketball hoop 3D dae model.
https://3dwarehouse.sketchup.com/model/fa42320b3def2c6b4741187cebbc52b3/Basketball-Hoop
I would first setup up the physicsShapes for the different elements.... backboard, pole & ring/hoop, floor & ball. I would then work out the cylinder size to fit inside the ring.
Using:
let cylinder = SCNCylinder(radius: 1.0, height: 0.1)
This becomes the physicBody for the hoop.
hoopNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry:cylinder))
I would then workout the collisions the ball has with each different basketball element/node.
Don’t forget to use the debug feature
SceneView.debugOptions = .showPhysicsShapes
This will help to visually debug the collisions with the physics shapes & make sure the physic shapes are accurately scaled and in the correct position.
How to do setup collisions has already been answered in a previous post here...
how to setup SceneKit collision detection
You probably want the ball to bounce off the backboard, pole and ring, but if it hits the hoop physic shape... you might want to make the ball disappear and create a nice spark/flame animation or something. You could then have a score that registers as well.
This Arkit game on github will give you a nice template for handling all those things, collisions, animations & scoring
https://github.com/farice/ARShooter
You have to implement it using the ball's world position and the basket world position + bounding box.
Calculate the size of the basket using it's bounding box:
var (basketBoundingBoxMin, basketBoundingBoxMax) = (basket?.presentation.boundingBox)!
let size = basketBoundingBoxMax - basketBoundingBoxMin
Use this size and the basket's world position to calculate:
Basket's minimum x,y,z
Basket's maximum x,y,z
Then check if ball's world position is inside the basket's minimum and maximum position.

Sprite-Kit: Applying physics to a projectile under the influence of moveTo

I am making a top down game where I am having cannons fire and having their projectiles move to the clicked location via the SKAction moveTo:duration. I am supposed to have wind change the trajectory so I have the cannonball implemented as an SKPhysicsBody and I am setting gravity to be a the windspeed since it is the only thing I can find that applies a constant force like wind would. The problem I am having is moveTo is probably the wrong way to be implementing the cannonball. The ball moves according to the path it should but then lands at the tapped location which is not what I want. I can't find a good alternative to moveTo. Any ideas?
You have to solve the projectile equations to determine the force needed and angle to applyImpulse. Solving the equation is only considering the gravity force and impulse force applied to projectile using the applyImpulse with your distances known from your cannons to user's click projectile destination.
Your applyImpulse launches the projectile, you start your wind and other external forces which will have an impact on the projectile path, changing it's destination from that of user's clicked.
You need to know few physics and math to re-arrange the equations and solve them :)
Not sure if you need to do all the advanced math, just set the angle of your cannon and apply impulse to the cannonball, and use the scene.physicsWorld.gravity as your wind, just make sure you also give your cannonball a physicsbody that has dynamic and affectedByGravity set to true.
To calculate the angle, you would do:
let angle = atan2(Double(touch.y - cannon.y),Double(touch.x - cannon.x))

SpriteKit - drawing circles containing other circles with physics body

I am new to Objective-C and I am trying to make a simple spriteKit game which contains a circle and a ball inside it. I want to move the ball around in this circle as well on the iPhone movement. So far I have created the circle and am able to put the ball on the screen.
My problem is that I am not sure the ball is actually inside the circle or on top of it. When I attach a physics body on the ball, it drops out of the screen and does not stop on the circle's bottom edge. I am using SKShapeNode for both the circle and ball.
Please help me to provide the right documentation to go through or a little piece of code that can resolve this.
You need to assign appropriate physics bodies to your nodes. See Simulating Physics in the Sprite Kit Programming Guide.
From your description, it sounds like you need to create the outter circle's physics body with the bodyWithEdgeLoopFromPath: method (and provide a path representing the circle). Note that an edge loop physics body is not dynamic and can only collide with volume-based bodies.
The inner balls physics body can be created with bodyWithCircleOfRadius:.

Setting Spritekit gravity source

Is there any way to set an x,y coordinate that gravity pulls towards?
We want to suck a number of objects with physicsbodies towards a point as if it was a black hole.
Not for the regular world gravity.
To achieve this effect, you have to apply to each body an impulse every frame. The strength and direction of the impulse depends on the distance of the body (node) to the gravity source's position.

Breakout Paddle Collision Angle

I'm making a Breakout clone and having a little trouble with the ball-to-paddle collisions. I have a rectangle represent both the ball and the paddle and when they intersect, the Y vector representing the ball's velocity is negated (as shown below). That all works fine. The problem is when the paddle is moving to the right I want it to nudge the ball a little to the right (as opposed to it just reflecting off normally) and I want the same to happen in the opposite direction is the paddle is moving to the left. I'm not sure how to go about doing this and I've looked all over. Any help would be appreciated. Thanks.
if (paddleRectangle.Intersects(ballRectangle))
{
ballVelocity.Y *= -1;
collision.Play(); //a collision sound
}
EDIT: Basically I want to slightly change the angle at which the ball bounces off the paddle based on which direction the paddle is moving. If the paddle is not moving, then the ball will bounce normally (by inverting the Y component of the ball's velocity)
Add the paddle's velocity vector to the paddle's normal vector (this basically bends the normal in the direction the paddle is moving) and normalize the result. Use this as the collision normal for reflection.
Vector2 collisionNormal = Vector2.Normalize(paddleNormal + (paddleVelocity * desiredEffectAmount));
ballVelocity = Vector2.Reflect(ballVelocity, collisionNormal);
i did some grinding in my head... and here are results. to achieve that you will need, moving direction of paddle, speed of paddle, ball speed, ball direction. and then by some math function calucalte angle and speed of bounce.
i think this image (if bouncing is phisicaly correct) will give you idea how to create this. can't help you with function that will handle this but i would go and try that way as in image.
You want a little friction, but probably not real friction.
Try scaling the paddle speed down by some factor and adding it to the ball velocity.

Resources