[ad_1]

**Background:** I’m creating an app in SpriteKit (swift) which features a 1-player Air Hockey bot mode. I have the bot working pretty well. However, I know an error with the code below. In the code, “botDistanceFromBall” should actually be “botDistanceFromIntersection”. The problem is the intersection point is based on the time to reach ball which is based on “botDistanceFromBall”. Therefore, I need a different way to calculate “botDistanceFromIntersection”. The former distance calculation is not accurate enough.

```
else if (ball!.position.y > frame.height * 0.50 && (((botPlayer!.position.y >= ball!.position.y) && (ballIsOnTarget() || ballCanReachTarget())) || (ballIsOnTarget() && ballCanReachTarget())) && botAttackSwitch == true)
{
//uses magnitude to see if ball can reach target, and slope of velocity vector (semi-infinite array) to determine if ball is on target
if ballIsOnTarget() == false && ballCanReachTarget() == true
{
let botDistanceFromBall = distance(botPlayer!.position, ball!.position)
let timeToReachBall = botDistanceFromBall / maxBotSpeed
//100 * 0.90^2 = 81
// scalar for multiplying velocity to predict position = 0.90^timetoreachball
let dampingEffect = (pow(ball!.physicsBody!.linearDamping, timeToReachBall))
let intersectionXPoint = ball!.position.x + (ball!.physicsBody!.velocity.dx * dampingEffect * timeToReachBall)
let intersectionYPoint = ball!.position.y + (ball!.physicsBody!.velocity.dy * dampingEffect * timeToReachBall)
let botPlayerXVelocity = (botPlayer!.position.x - intersectionXPoint) / timeToReachBall
let botPlayerYVelocity = (botPlayer!.position.y - intersectionYPoint) / timeToReachBall
if (intersectionXPoint > xEdgeWidth + ballRadius && intersectionXPoint < frame.width - xEdgeWidth - ballRadius) && intersectionYPoint > frame.height * 0.5 && intersectionYPoint < frame.height * 0.70 && intersectionYPoint < botPlayer!.position.y
{
botPlayer?.physicsBody?.velocity = CGVector(dx: -botPlayerXVelocity, dy: -botPlayerYVelocity)
}
```

**The question I’m asking is:** How do I calculate the intersection point given two points (botPosition and puck/ball position) and their velocity vectors (dx,dy). I know this question has been asked in other more conceptual contexts, but I am struggling to implement the linear algebra in swift.

The bot has a defined/fixed “maxBotSpeed”, while the puck’s velocity can vary.

[ad_2]