问题描述
我正在为我的大学工作开发太空入侵者的副本,但我在宇宙飞船的动画方面遇到了一些问题。飞船的移动应该根据玩家触摸的位置从屏幕中心向左或向右移动。但是,当飞船位置改变时,后面总会有一些帧跟在真实的飞船后面。这里有一个截图:
有些变量是法语,让我解释其中的一些: -spaceship.enMouvement : 显示运动方式:-1,向左,0,停止,1,向右。 -spaceship.bouge() : 改变飞船位置的方法。 宇宙飞船.kt:
package com.example.spaceinvaders2
import android.content.res.Resources
import android.graphics.*
import android.widget.Toast
class Spaceship(res: Resources) {
var x : Int =450
var y : Int =1000
var width : Int
var height: Int
var enMouvement = 0 //0 : à l'arrêt,-1 : vers la gauche,1 vers la droite
var img : Bitmap = BitmapFactory.decodeResource(res,R.drawable.space_ship)
val paint = Paint()
init {
width = img.width
height = img.height
width /= 15
height /= 15
img = Bitmap.createScaledBitmap(img,width,height,false)
}
fun draw(canvas: Canvas){
canvas.drawBitmap(img,x*1f,y*1f,paint)
}
fun bouge(){
x += 15*enMouvement
}
}
GameView.kt
package com.example.spaceinvaders2
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_game_view.view.*
import java.lang.Thread.sleep
class GameView @JvmOverloads constructor (context: Context,attributes: AttributeSet? = null,defStyleAttr: Int = 0): SurfaceView(context,attributes,defStyleAttr),Runnable,SurfaceHolder.Callback{
lateinit var thread: Thread
lateinit var canvas: Canvas
private var drawing = true //Si on joue = true,si on ne joue pas = false
private var spaceship = Spaceship(resources)
override fun run(){
while (drawing){
update()
draw()
sleep(17)
}
}
fun resume(){
//Si l'on revient sur l'application
drawing = true
thread = Thread(this)
thread.start()
}
fun pause(){
//Si l'on sort de l'application
drawing = false
thread.join()
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
//Le toucher sur l'écran change le sens du mvt du spaceship
when (event?.action){
MotionEvent.ACTION_DOWN ->
if (event.x < width/2) spaceship.enMouvement = -1
else if (event.x > width/2) spaceship.enMouvement = 1
MotionEvent.ACTION_UP -> spaceship.enMouvement = 0
}
return true
}
fun update(){
//Mettre les positions des objets à jour
spaceship.bouge()
}
fun draw(){
//Dessiner l'écran
if(holder.surface.isValid){
canvas = holder.lockCanvas()
spaceship.draw(canvas)
holder.unlockCanvasAndPost(canvas)
}
}
override fun surfaceChanged(holder: SurfaceHolder,format : Int,width: Int,height: Int){
}
override fun surfaceCreated(holder: SurfaceHolder){
thread = Thread(this)
thread.start()
}
override fun surfaceDestroyed(holder: SurfaceHolder){
thread.join()
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)