<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by mike83ke on Medium]]></title>
        <description><![CDATA[Stories by mike83ke on Medium]]></description>
        <link>https://medium.com/@miqel707?source=rss-f687cb8e4bea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u-Rfm8qOBQv1q76uWSlVWQ.png</url>
            <title>Stories by mike83ke on Medium</title>
            <link>https://medium.com/@miqel707?source=rss-f687cb8e4bea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:55:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miqel707/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Enhancing the Music Player UI: New Visual Dynamics with a Spinning Disc and a Revamped Playlist…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@miqel707/enhancing-the-music-player-ui-new-visual-dynamics-with-a-spinning-disc-and-a-revamped-playlist-c097e67e287a?source=rss-f687cb8e4bea------2"><img src="https://cdn-images-1.medium.com/max/1332/1*fUAXqnaRhkQchq5auidvog.png" width="1332"></a></p><p class="medium-feed-snippet">Tweaking UI in Music Player Application (MP3) in SwiftUI.</p><p class="medium-feed-link"><a href="https://medium.com/@miqel707/enhancing-the-music-player-ui-new-visual-dynamics-with-a-spinning-disc-and-a-revamped-playlist-c097e67e287a?source=rss-f687cb8e4bea------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@miqel707/enhancing-the-music-player-ui-new-visual-dynamics-with-a-spinning-disc-and-a-revamped-playlist-c097e67e287a?source=rss-f687cb8e4bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/c097e67e287a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-programming]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[mike83ke]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 22:31:57 GMT</pubDate>
            <atom:updated>2024-08-25T22:31:57.713Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding MVVM in SwiftUI: A Practical Guide #1 | Music Player Example]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@miqel707/understanding-mvvm-in-swiftui-a-practical-guide-1-music-player-example-becc90978aa5?source=rss-f687cb8e4bea------2"><img src="https://cdn-images-1.medium.com/max/1090/1*Y33wgxJAZxj4Lp8NmGfDtA.png" width="1090"></a></p><p class="medium-feed-snippet">In this guide, we will learn how to create Music Player App  in SwiftUI using the MVVM pattern.</p><p class="medium-feed-link"><a href="https://medium.com/@miqel707/understanding-mvvm-in-swiftui-a-practical-guide-1-music-player-example-becc90978aa5?source=rss-f687cb8e4bea------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@miqel707/understanding-mvvm-in-swiftui-a-practical-guide-1-music-player-example-becc90978aa5?source=rss-f687cb8e4bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/becc90978aa5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[mike83ke]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 12:48:57 GMT</pubDate>
            <atom:updated>2024-08-25T22:33:51.450Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building Dynamic Brick Animations in SwiftUI | SwiftUI Animation #2]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@miqel707/building-dynamic-brick-animations-in-swiftui-swiftui-animation-2-f87855e329c7?source=rss-f687cb8e4bea------2"><img src="https://cdn-images-1.medium.com/max/1058/1*nND177V6Fq_poeVJEvqWXw.png" width="1058"></a></p><p class="medium-feed-snippet">This tutorial walks you through creating engaging animations using SwiftUI&#x2019;s state management and animation features.</p><p class="medium-feed-link"><a href="https://medium.com/@miqel707/building-dynamic-brick-animations-in-swiftui-swiftui-animation-2-f87855e329c7?source=rss-f687cb8e4bea------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@miqel707/building-dynamic-brick-animations-in-swiftui-swiftui-animation-2-f87855e329c7?source=rss-f687cb8e4bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/f87855e329c7</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[mike83ke]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 16:09:56 GMT</pubDate>
            <atom:updated>2024-07-28T17:47:52.981Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Simulating a Washing Machine with SwiftUI | SwiftUI Animation #1]]></title>
            <link>https://medium.com/@miqel707/simulating-a-washing-machine-with-swiftui-swiftui-animation-1-86d7c26fc34f?source=rss-f687cb8e4bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d7c26fc34f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[mike83ke]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 18:44:42 GMT</pubDate>
            <atom:updated>2024-07-28T16:13:24.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXNVuVioJ8ycuDtg1CeICQ.png" /></figure><p>Creating simulations can be an exciting way to explore complex physical behaviors in a controlled environment. In this article, we will dive deep into building a simplified washing machine simulation using SwiftUI. This simulation involves basic UI elements to illustrate the underlying problem, complete with spinning circles representing clothes in a washing machine drum. Let’s walk through the entire process, from setup to execution, explaining each part of the code in detail.</p><p>Below is an animation of a given program, and at the end I add the entire code to copy, I encourage you to read it and write your observations.</p><p>Here’s animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*ElmbCuHdYCe5Rlk3gdbilQ.gif" /><figcaption>Wash machine animation in SwuftUI.</figcaption></figure><h3>The ContentView Structure</h3><p>Our main view, ContentView, will contain the core elements of the simulation: a large circle representing the drum, smaller circles representing clothes, and a button to start and stop the simulation.</p><pre>import SwiftUI<br>import Combine<br><br>struct ContentView: View {<br>    @State private var circles: [CircleModel] = []<br>    @State private var timer: Timer?<br>    @State private var currentAngularVelocity: CGFloat = 0<br>    @State private var currentRotation: Double = 0<br>    @State private var isAccelerating = true<br>    @State private var isRunning = false<br>    <br>    let largeCircleWidth: CGFloat = 300<br>    let largeCircleHeight: CGFloat = 300<br>    let maxSmallCircleRadius: CGFloat = 12.5<br>    let gravity: CGFloat = 9.8<br>    let bounceDamping: CGFloat = 0.5<br>    let friction: CGFloat = 0.9<br>    let maxAngularVelocity: CGFloat = 5<br>    <br>    var body: some View {<br>        VStack {<br>            ZStack {<br>                Circle()<br>                    .fill(Color(red: 200/255, green: 200/255, blue: 200/255))<br>                    .frame(width: largeCircleWidth, height: largeCircleHeight)<br>                <br>                DrumBackgroundShape()<br>                    .fill(Color.gray)<br>                    .frame(width: largeCircleWidth, height: largeCircleHeight)<br>                    .rotationEffect(.degrees(currentRotation))<br>                <br>                ForEach(circles) { circle in<br>                    Circle()<br>                        .fill(circle.color)<br>                        .frame(width: circle.radius * 2, height: circle.radius * 2)<br>                        .position(circle.position)<br>                }<br>            }<br>            .frame(width: largeCircleWidth, height: largeCircleHeight)<br>            <br>            Button(action: toggleSimulation) {<br>                Image(systemName: isRunning ? &quot;stop.circle.fill&quot; : &quot;play.circle.fill&quot;)<br>                    .resizable()<br>                    .frame(width: 50, height: 50)<br>                    .foregroundColor(.black)<br>            }<br>            .padding()<br>        }<br>    }<br></pre><h3>Explaining the ContentView</h3><ul><li><strong>State Variables</strong>: We declare several state variables to manage the circles, timer, angular velocity, rotation, and simulation state.</li><li><strong>Constants</strong>: We define constants for the drum size, maximum small circle radius, gravity, bounce damping, friction, and maximum angular velocity.</li><li><strong>Body</strong>: The body property contains the UI elements like:</li><li><strong>ZStack</strong>: It holds the drum circle, the rotating drum background, and the smaller circles representing clothes.</li><li><strong>Button</strong>: A button toggles the simulation, changing its icon based on whether the simulation is running.</li></ul><h3>Managing the Simulation</h3><p>We need functions to start, stop, and update the simulation.</p><h4>Toggling the Simulation</h4><pre>func toggleSimulation() {<br>    if isRunning {<br>        isRunning = false<br>    } else {<br>        startSimulation()<br>        isRunning = true<br>    }<br>}</pre><h4>Starting the Simulation</h4><pre>func startSimulation() {<br>    circles = createCircles()<br>    currentAngularVelocity = 0<br>    currentRotation = 0<br>    isAccelerating = true<br>    timer?.invalidate()<br>    timer = Timer.scheduledTimer(withTimeInterval: 0.016, repeats: true) { _ in<br>        updateCircles()<br>    }<br>}</pre><p><strong><em>withTimeInterval: 0.016</em></strong><em>:</em> This specifies the interval at which the timer fires. In this case, it is set to 0.016 seconds, which corresponds to approximately 60 frames per second (1 / 60 ≈ 0.016). This is a common frame rate for animations and simulations, providing smooth motion.</p><h4>Creating Circles</h4><pre>func createCircles() -&gt; [CircleModel] {<br>    var newCircles: [CircleModel] = []<br>    for i in 0..&lt;75 {<br>        let radius = CGFloat.random(in: 5...maxSmallCircleRadius)<br>        let angle = CGFloat.random(in: 0..&lt;2 * .pi)<br>        let maxRadius = min(largeCircleWidth, largeCircleHeight) / 2 - radius<br>        let distance = CGFloat.random(in: radius...maxRadius)<br>        let x = largeCircleWidth / 2 + distance * cos(angle)<br>        let y = largeCircleHeight / 2 + distance * sin(angle)<br>        let color: Color = i &lt; 35 ? Color(red: 113/255, green: 224/255, blue: 249/255) : Color(red: 40/255, green: 43/255, blue: 131/255)<br>        newCircles.append(CircleModel(id: UUID(), position: CGPoint(x: x, y: y), radius: radius, velocity: .zero, color: color))<br>    }<br>    return newCircles<br>}</pre><h3>Updating Circles</h3><pre>func updateCircles() {<br>    if isRunning {<br>        // Accelerating or decelerating the drum<br>        if isAccelerating {<br>            currentAngularVelocity += 0.005<br>            if currentAngularVelocity &gt;= maxAngularVelocity {<br>                isAccelerating = false<br>            }<br>        } else {<br>            currentAngularVelocity -= 0.005<br>            if currentAngularVelocity &lt;= -maxAngularVelocity {<br>                isAccelerating = true<br>            }<br>        }<br>    } else {<br>        // Slowing down the drum<br>        if currentAngularVelocity &gt; 0 {<br>            currentAngularVelocity -= 0.01<br>            if currentAngularVelocity &lt; 0 {<br>                currentAngularVelocity = 0<br>            }<br>        } else if currentAngularVelocity &lt; 0 {<br>            currentAngularVelocity += 0.01<br>            if currentAngularVelocity &gt; 0 {<br>                currentAngularVelocity = 0<br>            }<br>        }<br>    }<br>    <br>    currentRotation += Double(currentAngularVelocity * 360 * 0.016)<br>    <br>    for i in 0..&lt;circles.count {<br>        // Adding rotation<br>        let angle = atan2(circles[i].position.y - largeCircleHeight / 2, circles[i].position.x - largeCircleWidth / 2)<br>        let radius = sqrt(pow(circles[i].position.x - largeCircleWidth / 2, 2) + pow(circles[i].position.y - largeCircleHeight / 2, 2))<br>        <br>        let angularDisplacement = currentAngularVelocity * 0.016<br>        let newAngle = angle + angularDisplacement<br>        let newX = largeCircleWidth / 2 + radius * cos(newAngle)<br>        let newY = largeCircleHeight / 2 + radius * sin(newAngle)<br>        <br>        circles[i].position.x = newX<br>        circles[i].position.y = newY<br>        <br>        // Adding gravity<br>        circles[i].velocity.y += gravity * 0.016<br>        circles[i].position.x += circles[i].velocity.x<br>        circles[i].position.y += circles[i].velocity.y<br>        <br>        let distanceFromCenter = sqrt(pow(circles[i].position.x - largeCircleWidth / 2, 2) + pow(circles[i].position.y - largeCircleHeight / 2, 2))<br>        <br>        if distanceFromCenter + circles[i].radius &gt; min(largeCircleWidth, largeCircleHeight) / 2 {<br>            let collisionAngle = atan2(circles[i].position.y - largeCircleHeight / 2, circles[i].position.x - largeCircleWidth / 2)<br>            circles[i].position.x = largeCircleWidth / 2 + (min(largeCircleWidth, largeCircleHeight) / 2 - circles[i].radius) * cos(collisionAngle)<br>            circles[i].position.y = largeCircleHeight / 2 + (min(largeCircleWidth, largeCircleHeight) / 2 - circles[i].radius) * sin(collisionAngle)<br>            <br>            let normalX = cos(collisionAngle)<br>            let normalY = sin(collisionAngle)<br>            let dotProduct = circles[i].velocity.x * normalX + circles[i].velocity.y * normalY<br>            circles[i].velocity.x -= 2 * dotProduct * normalX * bounceDamping<br>            circles[i].velocity.y -= 2 * dotProduct * normalY * bounceDamping<br>            <br>            // Applying friction<br>            circles[i].velocity.x *= friction<br>            circles[i].velocity.y *= friction<br>        }<br>        <br>        for j in (i + 1)..&lt;circles.count {<br>            let dx = circles[j].position.x - circles[i].position.x<br>            let dy = circles[j].position.y - circles[i].position.y<br>            let distance = sqrt(dx * dx + dy * dy)<br>            <br>            if distance &lt; circles[i].radius + circles[j].radius {<br>                let collisionAngle = atan2(dy, dx)<br>                let targetX = circles[i].position.x + cos(collisionAngle) * (circles[i].radius + circles[j].radius)<br>                let targetY = circles[i].position.y + sin(collisionAngle) * (circles[i].radius + circles[j].radius)<br>                let ax = (targetX - circles[j].position.x) * 0.5<br>                let ay = (targetY - circles[j].position.y) * 0.5<br>                <br>                circles[i].velocity.x -= ax<br>                circles[i].velocity.y -= ay<br>                circles[j].velocity.x += ax<br>                circles[j].velocity.y += ay<br>                <br>                circles[i].position.x -= ax<br>                circles[i].position.y -= ay<br>                circles[j].position.x += ax<br>                circles[j].position.y += ay<br>            }<br>        }<br>    }<br>}</pre><p>Let’s break down and explain each part of the updateCircles function in detail. This function is responsible for updating the state of each circle in our simulation, including their positions, velocities, and handling collisions with the drum and with each other.</p><h3>Function Overview</h3><p>The updateCircles function performs several tasks:</p><ol><li>Updates the angular velocity and rotation of the drum.</li><li>Calculates the new positions of the circles based on the drum’s rotation and gravity.</li><li>Handles collisions between circles and the drum.</li><li>Handles collisions between circles themselves.</li></ol><h3>Code Breakdown</h3><h4>Angular Velocity and Drum Rotation</h4><pre>if isRunning {<br>    // Accelerating or decelerating the drum<br>    if isAccelerating {<br>        currentAngularVelocity += 0.005<br>        if currentAngularVelocity &gt;= maxAngularVelocity {<br>            isAccelerating = false<br>        }<br>    } else {<br>        currentAngularVelocity -= 0.005<br>        if currentAngularVelocity &lt;= -maxAngularVelocity {<br>            isAccelerating = true<br>        }<br>    }<br>} else {<br>    // Slowing down the drum<br>    if currentAngularVelocity &gt; 0 {<br>        currentAngularVelocity -= 0.01<br>        if currentAngularVelocity &lt; 0 {<br>            currentAngularVelocity = 0<br>        }<br>    } else if currentAngularVelocity &lt; 0 {<br>        currentAngularVelocity += 0.01<br>        if currentAngularVelocity &gt; 0 {<br>            currentAngularVelocity = 0<br>        }<br>    }<br>}</pre><ul><li><strong>isRunning</strong>: Checks if the simulation is currently running.</li><li><strong>isAccelerating</strong>: Manages the state of acceleration and deceleration of the drum.</li><li><strong>currentAngularVelocity</strong>: The rate of rotation of the drum, which increases or decreases based on whether the drum is accelerating or decelerating.</li><li><strong>maxAngularVelocity</strong>: The maximum allowed speed of the drum’s rotation.</li><li>If the drum is running and accelerating, the angular velocity increases until it hits the maximum limit. If decelerating, it decreases. When the simulation stops, the drum gradually slows down to a halt.</li></ul><pre>currentRotation += Double(currentAngularVelocity * 360 * 0.016)</pre><ul><li>Updates the current rotation of the drum based on the angular velocity. The multiplication by 360 * 0.016 converts the angular velocity to a rotational degree value over the 16-millisecond timer interval.</li></ul><h4>Updating Circle Positions</h4><pre>for i in 0..&lt;circles.count {<br>    // Adding rotation<br>    let angle = atan2(circles[i].position.y - largeCircleHeight / 2, circles[i].position.x - largeCircleWidth / 2)<br>    let radius = sqrt(pow(circles[i].position.x - largeCircleWidth / 2, 2) + pow(circles[i].position.y - largeCircleHeight / 2, 2))<br>    <br>    let angularDisplacement = currentAngularVelocity * 0.016<br>    let newAngle = angle + angularDisplacement<br>    let newX = largeCircleWidth / 2 + radius * cos(newAngle)<br>    let newY = largeCircleHeight / 2 + radius * sin(newAngle)<br>    <br>    circles[i].position.x = newX<br>    circles[i].position.y = newY</pre><ul><li><strong>angle</strong>: Calculates the current angle of the circle relative to the center of the drum.</li><li><strong>radius</strong>: Calculates the distance of the circle from the center of the drum.</li><li><strong>angularDisplacement</strong>: Calculates how much the circle should move due to the drum’s rotation.</li><li><strong>newX, newY</strong>: Calculate the new position of the circle based on the updated angle and radius.</li><li>Updates the position of each circle according to the drum’s rotation.</li></ul><h4>Applying Gravity</h4><pre>  circles[i].velocity.y += gravity * 0.016<br>  circles[i].position.x += circles[i].velocity.x<br>  circles[i].position.y += circles[i].velocity.y</pre><ul><li><strong>gravity</strong>: Simulates the gravitational force acting on the circles by increasing the y-velocity.</li><li><strong>velocity</strong>: Updates the circle’s position based on its current velocity.</li></ul><h4>Handling Drum Collisions</h4><pre>let distanceFromCenter = sqrt(pow(circles[i].position.x - largeCircleWidth / 2, 2) + pow(circles[i].position.y - largeCircleHeight / 2, 2))<br>    <br>    if distanceFromCenter + circles[i].radius &gt; min(largeCircleWidth, largeCircleHeight) / 2 {<br>        let collisionAngle = atan2(circles[i].position.y - largeCircleHeight / 2, circles[i].position.x - largeCircleWidth / 2)<br>        circles[i].position.x = largeCircleWidth / 2 + (min(largeCircleWidth, largeCircleHeight) / 2 - circles[i].radius) * cos(collisionAngle)<br>        circles[i].position.y = largeCircleHeight / 2 + (min(largeCircleWidth, largeCircleHeight) / 2 - circles[i].radius) * sin(collisionAngle)<br>        <br>        let normalX = cos(collisionAngle)<br>        let normalY = sin(collisionAngle)<br>        let dotProduct = circles[i].velocity.x * normalX + circles[i].velocity.y * normalY<br>        circles[i].velocity.x -= 2 * dotProduct * normalX * bounceDamping<br>        circles[i].velocity.y -= 2 * dotProduct * normalY * bounceDamping<br>        <br>        // Applying friction<br>        circles[i].velocity.x *= friction<br>        circles[i].velocity.y *= friction<br>    }</pre><ul><li><strong>distanceFromCenter</strong>: Calculates the distance of the circle from the center of the drum.</li><li>Checks if the circle has collided with the drum wall.</li><li><strong>collisionAngle</strong>: Calculates the angle of collision.</li><li>Adjusts the circle’s position to be just inside the drum boundary.</li><li><strong>normalX, normalY</strong>: Calculate the normal vector at the point of collision.</li><li><strong>dotProduct</strong>: Calculates the dot product for reflection.</li><li>Adjusts the velocity of the circle to simulate a bounce effect using the damping factor.</li><li>Applies friction to the circle’s velocity to simulate energy loss.</li></ul><h4>Handling Circle-to-Circle Collisions</h4><pre>for j in (i + 1)..&lt;circles.count {<br>        let dx = circles[j].position.x - circles[i].position.x<br>        let dy = circles[j].position.y - circles[i].position.y<br>        let distance = sqrt(dx * dx + dy * dy)<br>        <br>        if distance &lt; circles[i].radius + circles[j].radius {<br>            let collisionAngle = atan2(dy, dx)<br>            let targetX = circles[i].position.x + cos(collisionAngle) * (circles[i].radius + circles[j].radius)<br>            let targetY = circles[i].position.y + sin(collisionAngle) * (circles[i].radius + circles[j].radius)<br>            let ax = (targetX - circles[j].position.x) * 0.5<br>            let ay = (targetY - circles[j].position.y) * 0.5<br>            <br>            circles[i].velocity.x -= ax<br>            circles[i].velocity.y -= ay<br>            circles[j].velocity.x += ax<br>            circles[j].velocity.y += ay<br>            <br>            circles[i].position.x -= ax<br>            circles[i].position.y -= ay<br>            circles[j].position.x += ax<br>            circles[j].position.y += ay<br>        }<br>    }<br>}</pre><ul><li>Let’s provide a concise explanation of this code segment that handles collisions between circles within the washing machine drum simulation.</li></ul><h3>Code Breakdown</h3><p>This code is responsible for detecting and responding to collisions between pairs of circles in the simulation.</p><h4>Calculate Distance between Circles</h4><pre>let dx = circles[j].position.x - circles[i].position.x<br>let dy = circles[j].position.y - circles[i].position.y<br>let distance = sqrt(dx * dx + dy * dy)</pre><ul><li><strong>dx</strong> and <strong>dy</strong>: Calculate the horizontal and vertical distances between the two circles.</li><li><strong>distance</strong>: Computes the Euclidean distance between the centers of the two circles.</li></ul><h4>Check for Collision</h4><pre>if distance &lt; circles[i].radius + circles[j].radius {}</pre><ul><li>This condition checks if the distance between the centers of the two circles is less than the sum of their radii, indicating a collision.</li></ul><h4>Calculate Collision Response</h4><pre>let collisionAngle = atan2(dy, dx)<br>let targetX = circles[i].position.x + cos(collisionAngle) * (circles[i].radius + circles[j].radius)<br>let targetY = circles[i].position.y + sin(collisionAngle) * (circles[i].radius + circles[j].radius)<br>let ax = (targetX - circles[j].position.x) * 0.5<br>let ay = (targetY - circles[j].position.y) * 0.5</pre><ul><li><strong>collisionAngle</strong>: The angle of collision between the circles.</li><li><strong>targetX, targetY</strong>: The target positions where the circles should be moved to avoid overlap.</li><li><strong>ax, ay</strong>: Calculate adjustments needed to separate the circles evenly along the collision axis.</li></ul><h4>Adjust Velocities</h4><pre>circles[i].velocity.x -= ax<br>circles[i].velocity.y -= ay<br>circles[j].velocity.x += ax<br>circles[j].velocity.y += ay</pre><ul><li>Adjusts the velocities of the circles to reflect the collision impact.</li><li>Circle i has its velocity reduced by the adjustment values, while circle j has its velocity increased by the same values.</li></ul><h4>Adjust Positions</h4><pre>circles[i].position.x -= ax<br>circles[i].position.y -= ay<br>circles[j].position.x += ax<br>circles[j].position.y += ay</pre><ul><li>Similarly, adjusts the positions of the circles to prevent overlap.</li><li>Circle i is moved away from circle j by the adjustment values, and circle j is moved in the opposite direction.</li></ul><h3>The Drum Background</h3><p>To make the simulation visually appealing, we add a custom shape for the drum background.</p><h4>Drum Background Shape</h4><pre>struct DrumBackgroundShape: Shape {<br>    func path(in rect: CGRect) -&gt; Path {<br>        var path = Path()<br>        let center = CGPoint(x: rect.width / 2, y: rect.height / 2)<br>        let armWidth: CGFloat = 20<br>        let armLength: CGFloat = rect.width / 3<br>        <br>        for i in 0..&lt;3 {<br>            let angle = CGFloat(i) * 2 * .pi / 3<br>            let x1 = center.x + armWidth * cos(angle - .pi / 2)<br>            let y1 = center.y + armWidth * sin(angle - .pi / 2)<br>            let x2 = center.x + armWidth * cos(angle + .pi / 2)<br>            let y2 = center.y + armWidth * sin(angle + .pi / 2)<br>            let x3 = center.x + armLength * cos(angle)<br>            let y3 = center.y + armLength * sin(angle)<br>            <br>            path.move(to: center)<br>            path.addLine(to: CGPoint(x: x1, y: y1))<br>            path.addLine(to: CGPoint(x: x3, y: y3))<br>            path.addLine(to: CGPoint(x: x2, y: y2))<br>            path.closeSubpath()<br>        }<br>        <br>        return path<br>    }<br>}</pre><h3>CircleModel</h3><p>Finally, we define the CircleModel struct to represent each circle in the simulation.</p><pre>struct CircleModel: Identifiable {<br>    let id: UUID<br>    var position: CGPoint<br>    var radius: CGFloat<br>    var velocity: CGPoint<br>    var color: Color<br>}</pre><h3>Preview</h3><p>To preview our view, we add a ContentView_Previews struct.</p><pre>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><blockquote>If you’ve made it this far, I want to thank you for your time. I invite you to observe and give your reaction. Let me know what other content you would like to see. See you! 👋</blockquote><p><em>Here is the full code:</em></p><pre>import SwiftUI<br>import Combine<br><br>struct ContentView: View {<br>    @State private var circles: [CircleModel] = []<br>    @State private var timer: Timer?<br>    @State private var currentAngularVelocity: CGFloat = 0<br>    @State private var currentRotation: Double = 0<br>    @State private var isAccelerating = true<br>    @State private var isRunning = false<br>    <br>    let largeCircleWidth: CGFloat = 300<br>    let largeCircleHeight: CGFloat = 300<br>    let maxSmallCircleRadius: CGFloat = 12.5<br>    let gravity: CGFloat = 9.8<br>    let bounceDamping: CGFloat = 0.5<br>    let friction: CGFloat = 0.9<br>    let maxAngularVelocity: CGFloat = 5<br>    <br>    var body: some View {<br>        VStack {<br>            ZStack {<br>                Circle()<br>                    .fill(Color(red: 200/255, green: 200/255, blue: 200/255))<br>                    .frame(width: largeCircleWidth, height: largeCircleHeight)<br>                <br>                DrumBackgroundShape()<br>                    .fill(Color.gray)<br>                    .frame(width: largeCircleWidth, height: largeCircleHeight)<br>                    .rotationEffect(.degrees(currentRotation))<br>                <br>                ForEach(circles) { circle in<br>                    Circle()<br>                        .fill(circle.color)<br>                        .frame(width: circle.radius * 2, height: circle.radius * 2)<br>                        .position(circle.position)<br>                }<br>            }<br>            .frame(width: largeCircleWidth, height: largeCircleHeight)<br>            <br>            Button(action: toggleSimulation) {<br>                Image(systemName: isRunning ? &quot;stop.circle.fill&quot; : &quot;play.circle.fill&quot;)<br>                    .resizable()<br>                    .frame(width: 50, height: 50)<br>                    .foregroundColor(.black)<br>            }<br>            .padding()<br>        }<br>    }<br>    <br>    func toggleSimulation() {<br>        if isRunning {<br>            isRunning = false<br>        } else {<br>            startSimulation()<br>            isRunning = true<br>        }<br>    }<br>    <br>    func startSimulation() {<br>        circles = createCircles()<br>        currentAngularVelocity = 0<br>        currentRotation = 0<br>        isAccelerating = true<br>        timer?.invalidate()<br>        timer = Timer.scheduledTimer(withTimeInterval: 0.016, repeats: true) { _ in<br>            updateCircles()<br>        }<br>    }<br>    <br>    func createCircles() -&gt; [CircleModel] {<br>        var newCircles: [CircleModel] = []<br>        for i in 0..&lt;75 {<br>            let radius = CGFloat.random(in: 5...maxSmallCircleRadius)<br>            let angle = CGFloat.random(in: 0..&lt;2 * .pi)<br>            let maxRadius = min(largeCircleWidth, largeCircleHeight) / 2 - radius<br>            let distance = CGFloat.random(in: radius...maxRadius)<br>            let x = largeCircleWidth / 2 + distance * cos(angle)<br>            let y = largeCircleHeight / 2 + distance * sin(angle)<br>            let color: Color = i &lt; 35 ? Color(red: 113/255, green: 224/255, blue: 249/255) : Color(red: 40/255, green: 43/255, blue: 131/255)<br>            newCircles.append(CircleModel(id: UUID(), position: CGPoint(x: x, y: y), radius: radius, velocity: .zero, color: color))<br>        }<br>        return newCircles<br>    }<br>    <br>    func updateCircles() {<br>        if isRunning {<br>            if isAccelerating {<br>                currentAngularVelocity += 0.005<br>                if currentAngularVelocity &gt;= maxAngularVelocity {<br>                    isAccelerating = false<br>                }<br>            } else {<br>                currentAngularVelocity -= 0.005<br>                if currentAngularVelocity &lt;= -maxAngularVelocity {<br>                    isAccelerating = true<br>                }<br>            }<br>        } else {<br>            if currentAngularVelocity &gt; 0 {<br>                currentAngularVelocity -= 0.01<br>                if currentAngularVelocity &lt; 0 {<br>                    currentAngularVelocity = 0<br>                }<br>            } else if currentAngularVelocity &lt; 0 {<br>                currentAngularVelocity += 0.01<br>                if currentAngularVelocity &gt; 0 {<br>                    currentAngularVelocity = 0<br>                }<br>            }<br>        }<br>        <br>        currentRotation += Double(currentAngularVelocity * 360 * 0.016)<br>        <br>        for i in 0..&lt;circles.count {<br>            let angle = atan2(circles[i].position.y - largeCircleHeight / 2, circles[i].position.x - largeCircleWidth / 2)<br>            let radius = sqrt(pow(circles[i].position.x - largeCircleWidth / 2, 2) + pow(circles[i].position.y - largeCircleHeight / 2, 2))<br>            <br>            let angularDisplacement = currentAngularVelocity * 0.016<br>            let newAngle = angle + angularDisplacement<br>            let newX = largeCircleWidth / 2 + radius * cos(newAngle)<br>            let newY = largeCircleHeight / 2 + radius * sin(newAngle)<br>            <br>            circles[i].position.x = newX<br>            circles[i].position.y = newY<br>            <br>            circles[i].velocity.y += gravity * 0.016<br>            circles[i].position.x += circles[i].velocity.x<br>            circles[i].position.y += circles[i].velocity.y<br>            <br>            let distanceFromCenter = sqrt(pow(circles[i].position.x - largeCircleWidth / 2, 2) + pow(circles[i].position.y - largeCircleHeight / 2, 2))<br>            <br>            if distanceFromCenter + circles[i].radius &gt; min(largeCircleWidth, largeCircleHeight) / 2 {<br>                let collisionAngle = atan2(circles[i].position.y - largeCircleHeight / 2, circles[i].position.x - largeCircleWidth / 2)<br>                circles[i].position.x = largeCircleWidth / 2 + (min(largeCircleWidth, largeCircleHeight) / 2 - circles[i].radius) * cos(collisionAngle)<br>                circles[i].position.y = largeCircleHeight / 2 + (min(largeCircleWidth, largeCircleHeight) / 2 - circles[i].radius) * sin(collisionAngle)<br>                <br>                let normalX = cos(collisionAngle)<br>                let normalY = sin(collisionAngle)<br>                let dotProduct = circles[i].velocity.x * normalX + circles[i].velocity.y * normalY<br>                circles[i].velocity.x -= 2 * dotProduct * normalX * bounceDamping<br>                circles[i].velocity.y -= 2 * dotProduct * normalY * bounceDamping<br>                <br>                // Zastosowanie tarcia<br>                circles[i].velocity.x *= friction<br>                circles[i].velocity.y *= friction<br>            }<br>            <br>            for j in (i + 1)..&lt;circles.count {<br>                let dx = circles[j].position.x - circles[i].position.x<br>                let dy = circles[j].position.y - circles[i].position.y<br>                let distance = sqrt(dx * dx + dy * dy)<br>                <br>                if distance &lt; circles[i].radius + circles[j].radius {<br>                    let collisionAngle = atan2(dy, dx)<br>                    let targetX = circles[i].position.x + cos(collisionAngle) * (circles[i].radius + circles[j].radius)<br>                    let targetY = circles[i].position.y + sin(collisionAngle) * (circles[i].radius + circles[j].radius)<br>                    let ax = (targetX - circles[j].position.x) * 0.5<br>                    let ay = (targetY - circles[j].position.y) * 0.5<br>                    <br>                    circles[i].velocity.x -= ax<br>                    circles[i].velocity.y -= ay<br>                    circles[j].velocity.x += ax<br>                    circles[j].velocity.y += ay<br>                    <br>                    circles[i].position.x -= ax<br>                    circles[i].position.y -= ay<br>                    circles[j].position.x += ax<br>                    circles[j].position.y += ay<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct DrumBackgroundShape: Shape {<br>    func path(in rect: CGRect) -&gt; Path {<br>        var path = Path()<br>        let center = CGPoint(x: rect.width / 2, y: rect.height / 2)<br>        let armWidth: CGFloat = 20<br>        let armLength: CGFloat = rect.width / 3<br>        <br>        for i in 0..&lt;3 {<br>            let angle = CGFloat(i) * 2 * .pi / 3<br>            let x1 = center.x + armWidth * cos(angle - .pi / 2)<br>            let y1 = center.y + armWidth * sin(angle - .pi / 2)<br>            let x2 = center.x + armWidth * cos(angle + .pi / 2)<br>            let y2 = center.y + armWidth * sin(angle + .pi / 2)<br>            let x3 = center.x + armLength * cos(angle)<br>            let y3 = center.y + armLength * sin(angle)<br>            <br>            path.move(to: center)<br>            path.addLine(to: CGPoint(x: x1, y: y1))<br>            path.addLine(to: CGPoint(x: x3, y: y3))<br>            path.addLine(to: CGPoint(x: x2, y: y2))<br>            path.closeSubpath()<br>        }<br>        <br>        return path<br>    }<br>}<br><br>struct CircleModel: Identifiable {<br>    let id: UUID<br>    var position: CGPoint<br>    var radius: CGFloat<br>    var velocity: CGPoint<br>    var color: Color<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d7c26fc34f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>