Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamolkhon/fb8c769390ad56241d8abb8e5129da84 to your computer and use it in GitHub Desktop.
Save jamolkhon/fb8c769390ad56241d8abb8e5129da84 to your computer and use it in GitHub Desktop.
package com.mygdx.game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.Screen
import com.badlogic.gdx.ScreenAdapter
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import com.badlogic.gdx.utils.Array
class GameScreen : Screen by ScreenAdapter() {
private val camera = OrthographicCamera().apply { setToOrtho(false) }
private val world = World(Vector2.Zero, true)
private val renderer = Box2DDebugRenderer()
init {
walls()
balls()
Gdx.input.inputProcessor = object : InputAdapter() {
override fun keyUp(keycode: Int): Boolean {
Gdx.app.log("GameScreen", "applying impulse")
val bodies = Array<Body>()
world.getBodies(bodies)
if (bodies.notEmpty()) {
val body = bodies[0]
body.applyLinearImpulse(Vector2(1f.unit, 1f.unit), body.worldCenter, true)
}
return true
}
}
}
override fun resize(width: Int, height: Int) {
}
override fun render(delta: Float) {
camera.update()
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
world.step(1 / 60f, 6, 2)
renderer.render(world, camera.combined.scale(100f, 100f, 0f))
}
private fun walls() {
val bodyDef = BodyDef().apply {
type = BodyDef.BodyType.StaticBody
position.setZero()
}
val chainShape = ChainShape()
chainShape.createChain(arrayOf(
Vector2(10f.unit, 10f.unit),
Vector2(300f.unit, 10f.unit),
Vector2(300f.unit, 500f.unit),
Vector2(10f.unit, 500f.unit),
Vector2(10f.unit, 10f.unit)))
val fixtureDef = FixtureDef().apply {
shape = chainShape
friction = 1f
restitution = 1f
}
world.createBody(bodyDef).createFixture(fixtureDef)
chainShape.dispose()
}
private fun balls() {
val bodyDef = BodyDef().apply {
type = BodyDef.BodyType.DynamicBody
fixedRotation = true
linearDamping = 0.5f
angularDamping = 0.5f
position.set(30f.unit, 30f.unit)
}
val circleShape = CircleShape().apply {
position.setZero()
radius = 10f.unit
}
val fixtureDef = FixtureDef().apply {
shape = circleShape
friction = 0f
restitution = 0f
density = 0.1f
}
body = world.createBody(bodyDef).apply { createFixture(fixtureDef) }
circleShape.dispose()
}
override fun dispose() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment