Разноцветные шарики с физикой на экране Вечеринка
This commit is contained in:
1 parent
89899cc73d
commit
e60da725e5
3 files changed
+500
-43
No files matched your search
@@ -0,0 +1,460 @@
|
||||
package com.example.helponizer
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.Shader
|
||||
import android.util.AttributeSet
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.VelocityTracker
|
||||
import android.view.View
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.max
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* A small physics playground: colourful balls fall, bounce off each other
|
||||
* and the walls, and can be grabbed and thrown with a finger.
|
||||
*/
|
||||
class BallPhysicsView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyleAttr: Int = 0
|
||||
) : View(context, attrs, defStyleAttr) {
|
||||
|
||||
private class Ball(
|
||||
var x: Float,
|
||||
var y: Float,
|
||||
var vx: Float,
|
||||
var vy: Float,
|
||||
val radius: Float
|
||||
) {
|
||||
var held = false
|
||||
var shader: RadialGradient? = null
|
||||
var highlightRadius = 0f
|
||||
val mass: Float get() = radius * radius
|
||||
}
|
||||
|
||||
private val balls = mutableListOf<Ball>()
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val highlightPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE }
|
||||
private val shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.BLACK }
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
private val gravity = 900f * density
|
||||
private val wallRestitution = 0.78f
|
||||
private val ballRestitution = 0.82f
|
||||
private val airDrag = 0.999f
|
||||
private val maxSpeed = 3200f * density
|
||||
private val maxThrowSpeed = 2600f * density
|
||||
|
||||
private var heldBall: Ball? = null
|
||||
private var activePointerId = MotionEvent.INVALID_POINTER_ID
|
||||
private var grabOffsetX = 0f
|
||||
private var grabOffsetY = 0f
|
||||
private var velocityTracker: VelocityTracker? = null
|
||||
private var lastFrameTime = 0L
|
||||
private var running = false
|
||||
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
val now = System.nanoTime()
|
||||
if (lastFrameTime == 0L) lastFrameTime = now
|
||||
var dt = (now - lastFrameTime) / 1_000_000_000f
|
||||
lastFrameTime = now
|
||||
dt = dt.coerceIn(0f, 0.05f)
|
||||
if (dt > 0f) {
|
||||
update(dt)
|
||||
invalidate()
|
||||
}
|
||||
postOnAnimation(this)
|
||||
}
|
||||
}
|
||||
|
||||
private val colors = intArrayOf(
|
||||
Color.parseColor("#E53935"),
|
||||
Color.parseColor("#FB8C00"),
|
||||
Color.parseColor("#FDD835"),
|
||||
Color.parseColor("#43A047"),
|
||||
Color.parseColor("#00ACC1"),
|
||||
Color.parseColor("#1E88E5"),
|
||||
Color.parseColor("#8E24AA"),
|
||||
Color.parseColor("#D81B60"),
|
||||
Color.parseColor("#7CB342")
|
||||
)
|
||||
|
||||
init {
|
||||
isClickable = true
|
||||
isFocusable = true
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
start()
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
stop()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
override fun onVisibilityChanged(changedView: View, visibility: Int) {
|
||||
super.onVisibilityChanged(changedView, visibility)
|
||||
if (visibility == VISIBLE) start() else stop()
|
||||
}
|
||||
|
||||
override fun onWindowVisibilityChanged(visibility: Int) {
|
||||
super.onWindowVisibilityChanged(visibility)
|
||||
if (visibility == VISIBLE) start() else stop()
|
||||
}
|
||||
|
||||
private fun start() {
|
||||
if (running || !isAttachedToWindow) return
|
||||
if (visibility != VISIBLE || windowVisibility != VISIBLE) return
|
||||
running = true
|
||||
lastFrameTime = 0L
|
||||
postOnAnimation(tick)
|
||||
}
|
||||
|
||||
private fun stop() {
|
||||
running = false
|
||||
removeCallbacks(tick)
|
||||
releaseHeldBall(throwBall = false)
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
if (w <= 0 || h <= 0) return
|
||||
if (balls.isEmpty()) {
|
||||
spawnBalls(w.toFloat(), h.toFloat())
|
||||
} else {
|
||||
balls.forEach { ball ->
|
||||
ball.x = clamp(ball.x, ball.radius, w - ball.radius)
|
||||
ball.y = clamp(ball.y, ball.radius, h - ball.radius)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun spawnBalls(w: Float, h: Float) {
|
||||
balls.clear()
|
||||
val count = 9
|
||||
val minRadius = 22f * density
|
||||
val maxRadius = 38f * density
|
||||
var attempts = 0
|
||||
|
||||
while (balls.size < count && attempts < 500) {
|
||||
attempts++
|
||||
val radius = minRadius + Random.nextFloat() * (maxRadius - minRadius)
|
||||
if (w < radius * 2f || h < radius * 2f) continue
|
||||
val x = radius + Random.nextFloat() * (w - radius * 2f)
|
||||
val y = radius + Random.nextFloat() * (h * 0.55f - radius * 2f).coerceAtLeast(1f)
|
||||
if (balls.any { hypot(it.x - x, it.y - y) < it.radius + radius + 8f * density }) {
|
||||
continue
|
||||
}
|
||||
val color = colors[balls.size % colors.size]
|
||||
val ball = Ball(
|
||||
x = x,
|
||||
y = y,
|
||||
vx = (Random.nextFloat() - 0.5f) * 900f * density,
|
||||
vy = (Random.nextFloat() - 0.5f) * 300f * density,
|
||||
radius = radius
|
||||
)
|
||||
ball.shader = RadialGradient(
|
||||
-radius * 0.35f,
|
||||
-radius * 0.38f,
|
||||
radius * 1.45f,
|
||||
intArrayOf(lighten(color, 0.55f), color, darken(color, 0.35f)),
|
||||
floatArrayOf(0f, 0.55f, 1f),
|
||||
Shader.TileMode.CLAMP
|
||||
)
|
||||
ball.highlightRadius = radius * 0.18f
|
||||
balls.add(ball)
|
||||
}
|
||||
}
|
||||
|
||||
private fun update(dt: Float) {
|
||||
val steps = ceil(dt / (1f / 120f)).toInt().coerceIn(1, 4)
|
||||
val step = dt / steps
|
||||
repeat(steps) {
|
||||
stepPhysics(step)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stepPhysics(dt: Float) {
|
||||
val w = width.toFloat()
|
||||
val h = height.toFloat()
|
||||
if (w <= 0f || h <= 0f) return
|
||||
|
||||
for (ball in balls) {
|
||||
if (ball.held) continue
|
||||
|
||||
ball.vy += gravity * dt
|
||||
ball.vx *= airDrag
|
||||
ball.vy *= airDrag
|
||||
|
||||
val speed = hypot(ball.vx, ball.vy)
|
||||
if (speed > maxSpeed) {
|
||||
val scale = maxSpeed / speed
|
||||
ball.vx *= scale
|
||||
ball.vy *= scale
|
||||
}
|
||||
|
||||
ball.x += ball.vx * dt
|
||||
ball.y += ball.vy * dt
|
||||
|
||||
if (ball.x - ball.radius < 0f) {
|
||||
ball.x = ball.radius
|
||||
ball.vx = -ball.vx * wallRestitution
|
||||
} else if (ball.x + ball.radius > w) {
|
||||
ball.x = w - ball.radius
|
||||
ball.vx = -ball.vx * wallRestitution
|
||||
}
|
||||
|
||||
if (ball.y - ball.radius < 0f) {
|
||||
ball.y = ball.radius
|
||||
ball.vy = -ball.vy * wallRestitution
|
||||
} else if (ball.y + ball.radius > h) {
|
||||
ball.y = h - ball.radius
|
||||
if (abs(ball.vy) < 35f * density) {
|
||||
ball.vy = 0f
|
||||
} else {
|
||||
ball.vy = -ball.vy * wallRestitution
|
||||
}
|
||||
ball.vx *= 0.985f
|
||||
}
|
||||
}
|
||||
|
||||
for (i in balls.indices) {
|
||||
for (j in i + 1 until balls.size) {
|
||||
resolveCollision(balls[i], balls[j])
|
||||
}
|
||||
}
|
||||
|
||||
for (ball in balls) {
|
||||
ball.x = clamp(ball.x, ball.radius, w - ball.radius)
|
||||
ball.y = clamp(ball.y, ball.radius, h - ball.radius)
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveCollision(a: Ball, b: Ball) {
|
||||
var dx = b.x - a.x
|
||||
var dy = b.y - a.y
|
||||
var distance = hypot(dx, dy)
|
||||
val minDistance = a.radius + b.radius
|
||||
if (distance >= minDistance) return
|
||||
|
||||
if (distance < 0.0001f) {
|
||||
dx = 1f
|
||||
dy = 0f
|
||||
distance = 0.0001f
|
||||
}
|
||||
|
||||
val nx = dx / distance
|
||||
val ny = dy / distance
|
||||
val overlap = minDistance - distance
|
||||
|
||||
val aInvMass = if (a.held) 0f else 1f / a.mass
|
||||
val bInvMass = if (b.held) 0f else 1f / b.mass
|
||||
val invMassSum = aInvMass + bInvMass
|
||||
if (invMassSum <= 0f) return
|
||||
|
||||
val correction = overlap / invMassSum * 0.85f
|
||||
if (!a.held) {
|
||||
a.x -= nx * correction * aInvMass
|
||||
a.y -= ny * correction * aInvMass
|
||||
}
|
||||
if (!b.held) {
|
||||
b.x += nx * correction * bInvMass
|
||||
b.y += ny * correction * bInvMass
|
||||
}
|
||||
|
||||
val relativeVx = b.vx - a.vx
|
||||
val relativeVy = b.vy - a.vy
|
||||
val velocityAlongNormal = relativeVx * nx + relativeVy * ny
|
||||
if (velocityAlongNormal > 0f) return
|
||||
if (abs(velocityAlongNormal) < 8f * density) return
|
||||
|
||||
val impulse = -(1f + ballRestitution) * velocityAlongNormal / invMassSum
|
||||
val impulseX = impulse * nx
|
||||
val impulseY = impulse * ny
|
||||
|
||||
if (!a.held) {
|
||||
a.vx -= impulseX * aInvMass
|
||||
a.vy -= impulseY * aInvMass
|
||||
}
|
||||
if (!b.held) {
|
||||
b.vx += impulseX * bInvMass
|
||||
b.vy += impulseY * bInvMass
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
|
||||
for (ball in balls) {
|
||||
shadowPaint.color = Color.argb(26, 0, 0, 0)
|
||||
canvas.drawCircle(
|
||||
ball.x,
|
||||
ball.y + ball.radius * 0.22f,
|
||||
ball.radius * 0.98f,
|
||||
shadowPaint
|
||||
)
|
||||
|
||||
val save = canvas.save()
|
||||
canvas.translate(ball.x, ball.y)
|
||||
paint.shader = ball.shader
|
||||
canvas.drawCircle(0f, 0f, ball.radius, paint)
|
||||
paint.shader = null
|
||||
highlightPaint.alpha = 110
|
||||
canvas.drawCircle(
|
||||
-ball.radius * 0.34f,
|
||||
-ball.radius * 0.38f,
|
||||
ball.highlightRadius,
|
||||
highlightPaint
|
||||
)
|
||||
canvas.restoreToCount(save)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
val ball = findBallAt(event.x, event.y) ?: return false
|
||||
heldBall = ball
|
||||
activePointerId = event.getPointerId(0)
|
||||
ball.held = true
|
||||
ball.vx = 0f
|
||||
ball.vy = 0f
|
||||
grabOffsetX = ball.x - event.x
|
||||
grabOffsetY = ball.y - event.y
|
||||
|
||||
balls.remove(ball)
|
||||
balls.add(ball)
|
||||
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = VelocityTracker.obtain().also { it.addMovement(event) }
|
||||
parent?.requestDisallowInterceptTouchEvent(true)
|
||||
performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)
|
||||
invalidate()
|
||||
return true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val ball = heldBall ?: return false
|
||||
val index = event.findPointerIndex(activePointerId)
|
||||
if (index < 0) {
|
||||
releaseHeldBall(throwBall = false)
|
||||
return false
|
||||
}
|
||||
velocityTracker?.addMovement(event)
|
||||
|
||||
val targetX = event.getX(index) + grabOffsetX
|
||||
val targetY = event.getY(index) + grabOffsetY
|
||||
ball.x = clamp(targetX, ball.radius, width - ball.radius)
|
||||
ball.y = clamp(targetY, ball.radius, height - ball.radius)
|
||||
invalidate()
|
||||
return true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_UP -> {
|
||||
val ball = heldBall ?: return false
|
||||
ball.vx = 0f
|
||||
ball.vy = 0f
|
||||
if (event.getPointerId(event.actionIndex) == activePointerId) {
|
||||
velocityTracker?.computeCurrentVelocity(1000, maxThrowSpeed)
|
||||
val throwVx = velocityTracker?.getXVelocity(activePointerId) ?: 0f
|
||||
val throwVy = velocityTracker?.getYVelocity(activePointerId) ?: 0f
|
||||
ball.vx = if (throwVx.isFinite()) {
|
||||
throwVx.coerceIn(-maxThrowSpeed, maxThrowSpeed)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
ball.vy = if (throwVy.isFinite()) {
|
||||
throwVy.coerceIn(-maxThrowSpeed, maxThrowSpeed)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
}
|
||||
releaseHeldBall(throwBall = true)
|
||||
performClick()
|
||||
return true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_CANCEL -> {
|
||||
if (heldBall == null) return false
|
||||
releaseHeldBall(throwBall = false)
|
||||
return true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_POINTER_UP -> {
|
||||
if (heldBall != null && event.getPointerId(event.actionIndex) == activePointerId) {
|
||||
releaseHeldBall(throwBall = false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.onTouchEvent(event)
|
||||
}
|
||||
|
||||
private fun releaseHeldBall(throwBall: Boolean) {
|
||||
val ball = heldBall ?: return
|
||||
ball.held = false
|
||||
if (!throwBall) {
|
||||
ball.vx = 0f
|
||||
ball.vy = 0f
|
||||
}
|
||||
heldBall = null
|
||||
activePointerId = MotionEvent.INVALID_POINTER_ID
|
||||
velocityTracker?.recycle()
|
||||
velocityTracker = null
|
||||
parent?.requestDisallowInterceptTouchEvent(false)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun findBallAt(x: Float, y: Float): Ball? {
|
||||
for (index in balls.indices.reversed()) {
|
||||
val ball = balls[index]
|
||||
if (hypot(ball.x - x, ball.y - y) <= ball.radius + 12f * density) {
|
||||
return ball
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override fun performClick(): Boolean {
|
||||
super.performClick()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun clamp(value: Float, minValue: Float, maxValue: Float): Float {
|
||||
return value.coerceIn(minValue, max(minValue, maxValue))
|
||||
}
|
||||
|
||||
private fun lighten(color: Int, fraction: Float): Int {
|
||||
val red = Color.red(color)
|
||||
val green = Color.green(color)
|
||||
val blue = Color.blue(color)
|
||||
return Color.rgb(
|
||||
(red + (255 - red) * fraction).toInt().coerceIn(0, 255),
|
||||
(green + (255 - green) * fraction).toInt().coerceIn(0, 255),
|
||||
(blue + (255 - blue) * fraction).toInt().coerceIn(0, 255)
|
||||
)
|
||||
}
|
||||
|
||||
private fun darken(color: Int, fraction: Float): Int {
|
||||
val red = Color.red(color)
|
||||
val green = Color.green(color)
|
||||
val blue = Color.blue(color)
|
||||
return Color.rgb(
|
||||
(red * (1f - fraction)).toInt().coerceIn(0, 255),
|
||||
(green * (1f - fraction)).toInt().coerceIn(0, 255),
|
||||
(blue * (1f - fraction)).toInt().coerceIn(0, 255)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,9 @@
|
||||
package com.example.helponizer
|
||||
|
||||
import android.content.Intent
|
||||
import android.graphics.RenderEffect
|
||||
import android.graphics.Shader
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
|
||||
@@ -16,20 +12,27 @@ class funny : BaseActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
setContentView(R.layout.activity_funny)
|
||||
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
|
||||
|
||||
val root = findViewById<View>(R.id.main)
|
||||
val baseLeft = root.paddingLeft
|
||||
val baseTop = root.paddingTop
|
||||
val baseRight = root.paddingRight
|
||||
val baseBottom = root.paddingBottom
|
||||
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
|
||||
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
|
||||
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
|
||||
view.setPadding(
|
||||
baseLeft + systemBars.left,
|
||||
baseTop + systemBars.top,
|
||||
baseRight + systemBars.right,
|
||||
baseBottom + systemBars.bottom
|
||||
)
|
||||
insets
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val blur = RenderEffect.createBlurEffect(20f, 20f, Shader.TileMode.CLAMP)
|
||||
findViewById<View>(R.id.main).setRenderEffect(blur)
|
||||
}
|
||||
|
||||
findViewById<View>(R.id.buttonOnMain).setOnClickListener {
|
||||
startActivity(Intent(this, MainActivity::class.java))
|
||||
finish()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
|
||||
@@ -1,43 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:id="@+id/main"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="?android:attr/colorBackground"
|
||||
android:fillViewport="true"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="24dp"
|
||||
android:paddingTop="32dp"
|
||||
android:paddingEnd="24dp"
|
||||
android:paddingBottom="24dp"
|
||||
tools:context=".funny">
|
||||
|
||||
<LinearLayout
|
||||
<TextView
|
||||
style="@style/ScreenTitle"
|
||||
android:layout_marginTop="16dp"
|
||||
android:gravity="center"
|
||||
android:text="@string/funny_title" />
|
||||
|
||||
<com.example.helponizer.BallPhysicsView
|
||||
android:id="@+id/ballField"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="24dp"
|
||||
android:paddingTop="32dp"
|
||||
android:paddingEnd="24dp"
|
||||
android:paddingBottom="24dp">
|
||||
<TextView
|
||||
style="@style/ScreenTitle"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/funny_title"
|
||||
android:gravity="center"/>
|
||||
android:layout_height="0dp"
|
||||
android:layout_marginTop="16dp"
|
||||
android:layout_marginBottom="16dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<Space
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:minHeight="28dp" />
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/buttonOnMain"
|
||||
style="@style/PrimaryButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp"
|
||||
android:text="@string/button_back_to_main"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/buttonOnMain"
|
||||
style="@style/PrimaryButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="35dp"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/button_back_to_main"
|
||||
android:textSize="15sp"/>
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
</LinearLayout>
|
||||
Reference in new issue
Block a user