libgdx地面不起作用

时间:2017-10-22 14:45:42

标签: java libgdx kotlin

我跟随本教程https://github.com/libgdx/libgdx/wiki/Box2d,我目前停留在静态对象上。这是我的游戏课程:

package com.mygdx.physics

import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.World
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.physics.box2d.CircleShape
import com.badlogic.gdx.physics.box2d.FixtureDef
import com.badlogic.gdx.physics.box2d.Fixture
import com.badlogic.gdx.physics.box2d.BodyDef
import com.badlogic.gdx.physics.box2d.PolygonShape



class Physics : ApplicationAdapter() {
    internal var batch: SpriteBatch? = null
    internal var world: World = World(Vector2(0.toFloat(), -10.toFloat()), true)
    internal var camera: OrthographicCamera = OrthographicCamera()
    internal var debugRenderer: Box2DDebugRenderer? = null
    internal var bodyDef: BodyDef = BodyDef()
    internal var body: Body? = null

    private var groundBodyDef: BodyDef = BodyDef()
    private var groundBox: PolygonShape = PolygonShape()
    private var groundBody: Body? = null

    override fun create() {
        createBody()
        createBall()
        createGround()

        camera.setToOrtho(false, 800f, 480f)
        debugRenderer = Box2DDebugRenderer()
    }

    override fun render() {
        Gdx.gl.glClearColor(1f, 0f, 0f, 1f)
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

        camera.update()
        debugRenderer?.render(world, camera.combined);
        world.step(1/45f, 6, 2);
    }

    override fun dispose() {
    }

    private fun createBody() {
      bodyDef.type = BodyType.DynamicBody
      bodyDef.position.set(100.toFloat(), 300.toFloat())
      body = world.createBody(bodyDef)
    }

    private fun createBall() {
      BallHandler(body).createBall()
    }

    private fun createGround() {
      groundBodyDef = BodyDef()
      groundBodyDef.position.set(Vector2(0f, 10f))

      groundBody = world.createBody(groundBodyDef)

      groundBox = PolygonShape()
      groundBox.setAsBox(camera.viewportWidth, 10.0f)
      groundBody?.createFixture(groundBox, 0.0f)
      groundBox.dispose()
    }
}

正如您所看到的,我以几乎相同的方式实现它。他们的球部分就像一个魅力,其余的正在编译,但我看不到创造的地面,也看不到它的影响。为什么这样或者我怎样才能有效地调试呢?

1 个答案:

答案 0 :(得分:1)

这是您的create方法:

override fun create() {
    createBody()
    createBall()
    createGround()

    camera.setToOrtho(false, 800f, 480f)
    debugRenderer = Box2DDebugRenderer()
}

您在致电createGround后设置了相机尺寸,但createGround已使用camera.viewportWidth。因此,地体的宽度为零。

将调用移至setToOrtho到方法的开头。

此外,这里有一个Kotlin提示:不是使用许多可空变量,而是使用lateinit properties来避免所有不必要的空值检查。

您也可以改为使用某些字段作为局部变量,例如groundBodyDef