vue实现人物跑动
实现人物跑动的Vue方案
使用CSS动画控制人物移动
在Vue组件中定义CSS动画关键帧,通过transform属性实现水平移动效果。人物跑动动画需要配合精灵图或连续帧动画。
<template>
<div class="character" :style="{ left: position + 'px' }"></div>
</template>
<script>
export default {
data() {
return {
position: 0,
speed: 5
}
},
mounted() {
setInterval(() => {
this.position += this.speed
}, 50)
}
}
</script>
<style>
.character {
width: 50px;
height: 80px;
background-image: url('character-sprite.png');
background-position: 0 0;
position: absolute;
bottom: 0;
animation: run 0.8s steps(6) infinite;
}
@keyframes run {
from { background-position: 0 0; }
to { background-position: -300px 0; }
}
</style>
使用GSAP动画库
GSAP提供更流畅的动画控制,适合复杂的人物运动场景。安装GSAP后可通过时间线管理动画序列。
npm install gsap
<template>
<div ref="character" class="character"></div>
</template>
<script>
import { gsap } from 'gsap'
export default {
mounted() {
gsap.to(this.$refs.character, {
x: 500,
duration: 3,
ease: "power1.inOut",
repeat: -1,
yoyo: true
})
}
}
</script>
响应键盘事件控制移动
通过监听键盘事件实现用户控制的人物跑动,适用于游戏场景。
<template>
<div
class="character"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
></div>
</template>
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
speed: 10,
keys: {}
}
},
created() {
window.addEventListener('keydown', this.keyDown)
window.addEventListener('keyup', this.keyUp)
},
methods: {
keyDown(e) {
this.keys[e.key] = true
},
keyUp(e) {
this.keys[e.key] = false
},
updatePosition() {
if (this.keys['ArrowRight']) this.position.x += this.speed
if (this.keys['ArrowLeft']) this.position.x -= this.speed
requestAnimationFrame(this.updatePosition)
}
},
mounted() {
this.updatePosition()
}
}
</script>
使用Vue过渡效果
Vue内置的过渡系统可以实现人物在不同状态间的平滑移动,适合场景切换时的角色移动。
<template>
<transition name="run">
<div v-if="visible" class="character"></div>
</transition>
</template>
<style>
.run-enter-active, .run-leave-active {
transition: all 1s ease;
}
.run-enter-from {
transform: translateX(-100px);
}
.run-leave-to {
transform: translateX(100px);
}
</style>
结合Canvas实现高性能动画
对于复杂游戏场景,使用Canvas渲染可以获得更好的性能表现。
<template>
<canvas ref="gameCanvas" width="800" height="600"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.gameCanvas
const ctx = canvas.getContext('2d')
let x = 0
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(characterImage, x, 300, 50, 80)
x += 5
if (x > canvas.width) x = 0
requestAnimationFrame(animate)
}
animate()
}
}
</script>
每种方案适用于不同场景,CSS动画适合简单UI动画,GSAP适合复杂时间线控制,键盘控制适合交互游戏,Canvas适合高性能需求场景。根据项目需求选择最合适的实现方式。







