我正在尝试使用Swift制作游戏Pong,但不使用SpriteKit
。到目前为止,我已经能够在视图上成功绘制一个矩形,并且能够在屏幕上拖动它。这是我当前的代码:
import UIKit class PongView: UIView { lazy var paddle: CGRect = { return CGRect(x: 200, y: 200, width: self.frame.width / 6, height: self.frame.height / 60) }() var movePaddle = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let gesture = UIPanGestureRecognizer(target: self, action: #selector(dragPaddle(recognizer:))) addGestureRecognizer(gesture) } override func draw(_ rect: CGRect) { drawPaddle(rect) } func drawPaddle(_ rect: CGRect) { let path = UIBezierPath(rect: paddle) UIColor.black.set() path.fill() } func paddleInBounds() -> Bool { //padding vars are calculated in another file return (paddle.minX >= frame.minX + leftPadding) && (paddle.maxX <= frame.maxX - rightPadding) && (paddle.minY >= frame.minY + topPadding) && (paddle.maxY <= frame.maxY - bottomPadding) } func setPaddleInBounds() { if (paddle.minX frame.maxX - rightPadding) { paddle.origin.x = frame.maxX - rightPadding - paddle.width } if (paddle.minY frame.maxY - bottomPadding) { paddle.origin.y = frame.maxY - bottomPadding - paddle.height } } @objc func dragPaddle(recognizer: UIPanGestureRecognizer) { print(paddle.origin) print(paddle.minX) print(paddle.minY) if paddleInBounds() { let translation = recognizer.translation(in: self) paddle.origin = CGPoint(x: paddle.minX + translation.x, y: paddle.minY + translation.y) recognizer.setTranslation(CGPoint.zero, in: self) setNeedsDisplay() } else { setPaddleInBounds() } } }
现在,我想创建一个球。不过,我不确定如何开始。碰撞应该很容易:
if (ball coordinates are within boundaries) || (ball coordinates touch paddle coordinates) { //collision detected }
但是,如果没有SpriteKit
,我不确定如何计算球的弹跳角度并相应地移动球,这是游戏的主要部分。有什么建议么?