如何制作这个浮动视图动画

问题描述

如何使用 uiviews 在 swift uikit 中制作这个浮动视图动画

  • 每个视图不会相互折叠。
  • 每个视图位置随机到 16 像素且移动缓慢。

我已尝试使用此代码 并多次调用推送功能

导入 UIKit

lazy var collision: uicollisionbehavior = {
    let collision = uicollisionbehavior()
    collision.translatesReferenceBoundsIntoBoundary = true
    collision.collisionDelegate = self
    collision.collisionMode = .everything
    return collision
}()

lazy var itemBehavIoUr: UIDynamicItemBehavior = {
    let behavIoU = UIDynamicItemBehavior()
    behavIoU.allowsRotation = false
    return behavIoU
}()

func addingPushBehavIoUr(onView view: UIDynamicItem,animationAdded: Bool = false) {
    let push = UIPushBehavior(items: [view],mode: .instantaneous)
   
    push.angle = CGFloat(arc4random())
    push.magnitude = 0.005
    
    push.action = { [weak self] in
        self?.removeChildBehavior(push)
    }
    addChildBehavior(push)
}

func addItem(withItem item: UIDynamicItem) {
    collision.addItem(item)
    itemBehavIoUr.addItem(item)
    addingPushBehavIoUr(onView: item)
}

override init() {
    super.init()
    addChildBehavior(collision)
    addChildBehavior(itemBehavIoUr)
}

var mainView: UIView?
convenience init(animator: UIDynamicAnimator,onView: UIView) {
    self.init()
    self.mainView = onView
    animator.addBehavior(self)
    
}

解决方法

将您的视图设置为正方形,使用 backroundColor 和 cornerRadius = height/2 获得您在示例中显示的圆形彩色视图。

使用 UIViewPropertyAnimator 以几秒钟的持续时间创建 UIView 动画,在该动画中,您将每个视图动画到一个位置,该位置与它的“锚点”位置在每个维度上的随机距离 UIViewPropertyAnimator 创建动画。您应该可以在网上找到大量示例。)

,

如果我错了,请纠正我,但听起来这里有两个任务:1) 用不重叠的球随机填充屏幕,以及 2) 让这些球漂浮在周围,以便它们在碰撞时相互反弹.

如果问题是动画生涩,那么为什么不放弃UIDynamicAnimator并从头开始编写物理?摆弄 Apple 库中的简陋功能可能会浪费无数个小时,因此请走稳妥的路线。数学很简单,而且您可以直接控制帧速率。

保留球及其速度的列表:

var balls = [UIView]()
var xvel = [CGFloat]()
var yvel = [CGFloat]()
let fps = 60.0

创建球时,随机生成一个不与任何其他球重叠的位置:

for _ in 0 ..< 6 {
    let ball = UIView(frame: CGRect(x: 0,y: 0,width: ballSize,height: ballSize))
    ball.layer.cornerRadius = ballSize / 2
    ball.backgroundColor = .green
    // Try random positions until we find something valid
    while true {
        ball.frame.origin = CGPoint(x: .random(in: 0 ... view.frame.width - ballSize),y: .random(in: 0 ... view.frame.height - ballSize))
        // Check for collisions
        if balls.allSatisfy({ !doesCollide($0,ball) }) { break }
    }
    view.addSubview(ball)
    balls.append(ball)
    // Randomly generate a direction
    let theta = CGFloat.random(in: -.pi ..< .pi)
    let speed: CGFloat = 20     // Pixels per second
    xvel.append(cos(theta) * speed)
    yvel.append(sin(theta) * speed)
}

然后在后台线程上运行一个 while 循环,以您想要的频率更新位置:

let timer = Timer(fire: .init(),interval: 1 / fps,repeats: true,block: { _ in
    
    // Apply movement
    for i in 0 ..< self.balls.count {
        self.move(ball: i)
    }
    // Check for collisions
    for i in 0 ..< self.balls.count {
        for j in 0 ..< self.balls.count {
            if i != j && self.doesCollide(self.balls[i],self.balls[j]) {
                // Calculate the normal vector between the two balls
                let nx = self.balls[j].center.x - self.balls[i].center.x
                let ny = self.balls[j].center.y - self.balls[i].center.y
                // Reflect both balls
                self.reflect(ball: i,nx: nx,ny: ny)
                self.reflect(ball: j,nx: -nx,ny: -ny)
                // Move both balls out of each other's hitboxes
                self.move(ball: i)
                self.move(ball: j)
            }
        }
    }
    // Check for boundary collision
    for (i,ball) in self.balls.enumerated() {
        if ball.frame.minX < 0 { self.balls[i].frame.origin.x = 0; self.xvel[i] *= -1 }
        if ball.frame.maxX > self.view.frame.width { self.balls[i].frame.origin.x = self.view.frame.width - ball.frame.width; self.xvel[i] *= -1 }
        if ball.frame.minY < 0 { self.balls[i].frame.origin.y = 0; self.yvel[i] *= -1 }
        if ball.frame.maxY > self.view.frame.height { self.balls[i].frame.origin.y = self.view.frame.height - ball.frame.height; self.yvel[i] *= -1 }
    }
})
RunLoop.current.add(timer,forMode: .common)

以下是辅助函数:

func move(ball i: Int) {
    balls[i].frame = balls[i].frame.offsetBy(dx: self.xvel[i] / CGFloat(fps),dy: self.yvel[i] / CGFloat(fps))
}
func reflect(ball: Int,nx: CGFloat,ny: CGFloat) {
    
    // Normalize the normal
    let normalMagnitude = sqrt(nx * nx + ny * ny)
    let nx = nx / normalMagnitude
    let ny = ny / normalMagnitude
    // Calculate the dot product of the ball's velocity with the normal
    let dot = xvel[ball] * nx + yvel[ball] * ny
    // Use formula to calculate the reflection. Explanation: https://chicio.medium.com/how-to-calculate-the-reflection-vector-7f8cab12dc42
    let rx = -(2 * dot * nx - xvel[ball])
    let ry = -(2 * dot * ny - yvel[ball])
    
    // Only apply the reflection if the ball is heading in the same direction as the normal
    if xvel[ball] * nx + yvel[ball] * ny >= 0 {
        xvel[ball] = rx
        yvel[ball] = ry
    }
}
func doesCollide(_ a: UIView,_ b: UIView) -> Bool {
    let radius = a.frame.width / 2
    let distance = sqrt(pow(a.center.x - b.center.x,2) + pow(a.center.y - b.center.y,2))
    return distance <= 2 * radius
}

结果

https://imgur.com/a/SoJ0mcL

如果出现任何问题,请告诉我,我非常乐意提供帮助。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...