uniapp 模拟小球碰撞
时间: 2023-07-24 12:16:08 浏览: 202
你可以使用uniapp来模拟小球碰撞。下面是一个简单的示例代码:
```html
<template>
<view class="container">
<view class="ball" v-for="(ball, index) in balls" :key="index" :style="{ top: ball.y + 'px', left: ball.x + 'px' }"></view>
</view>
</template>
<script>
export default {
data() {
return {
balls: [
{ x: 100, y: 100, vx: 2, vy: 3 },
{ x: 200, y: 200, vx: -3, vy: -2 },
],
containerWidth: 400,
containerHeight: 400,
};
},
mounted() {
this.animationLoop();
},
methods: {
animationLoop() {
setInterval(() => {
this.moveBalls();
this.checkCollision();
}, 16);
},
moveBalls() {
for (let ball of this.balls) {
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.x < 0 || ball.x > this.containerWidth) {
ball.vx *= -1;
}
if (ball.y < 0 || ball.y > this.containerHeight) {
ball.vy *= -1;
}
}
},
checkCollision() {
for (let i = 0; i < this.balls.length; i++) {
for (let j = i + 1; j < this.balls.length; j++) {
let ball1 = this.balls[i];
let ball2 = this.balls[j];
let dx = ball2.x - ball1.x;
let dy = ball2.y - ball1.y;
let distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 20) {
// 两球碰撞,交换速度
let tempVx = ball1.vx;
let tempVy = ball1.vy;
ball1.vx = ball2.vx;
ball1.vy = ball2.vy;
ball2.vx = tempVx;
ball2.vy = tempVy;
}
}
}
},
},
};
</script>
<style>
.container {
width: 400px;
height: 400px;
position: relative;
}
.ball {
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
position: absolute;
}
</style>
```
这个示例代码使用了uniapp的模板语法和计算属性,通过设置小球的初始位置和速度,在每一帧中更新小球的位置,并检测小球之间是否发生碰撞。如果两个小球距离小于20像素,则交换它们的速度。你可以根据自己的需求修改代码并添加更多的小球。
阅读全文