由于某种原因,在我的世界中,物理方向被反转。我的意思是-9.8引力的作用就像9.8引力,所以物体也在上升。水平速度也是反转的。对于x,y坐标系统,一定有问题。
world = World(Vector2(0f,-9.8f),false)向上推动对象
PPM有问题吗?
package com.mygdx.game
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.physics.box2d.World
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer
class MyGdxGame : ApplicationAdapter() {
val PPM = 32f
private lateinit var camera : OrthographicCamera
private lateinit var world :World
private lateinit var player:Body
private lateinit var platform:Body
private lateinit var b2dr:Box2DDebugRenderer
override fun create() {
var w = Gdx.graphics.width
var h = Gdx.graphics.height
camera = OrthographicCamera()
camera.setToOrtho(false, w / 2f, h / 2f)
world = World(Vector2(0f,-9.8f),false)
b2dr = Box2DDebugRenderer()
player = createBox(2f,10f,32,32,false)
platform = createBox(0f,0f,64,32,true)
}
override fun render() {
update(Gdx.graphics.deltaTime)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
b2dr.render(world,camera.combined.scl(PPM))
}
override fun resize(width: Int, height: Int) {
camera.setToOrtho(false, width / 2f, height / 2f)
}
override fun dispose() {
world.dispose()
b2dr.dispose()
}
fun update(delta:Float){
world.step(1/60f,6,2)
inputUpdate(delta)
cameraUpdate(delta)
}
fun inputUpdate(delta:Float){
var horizontalForce = 0f;
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
horizontalForce -=1
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
horizontalForce +=1
}
if(Gdx.input.isKeyJustPressed(Input.Keys.UP)){
player.applyForceToCenter(0f,300f,false)
}
player.setLinearVelocity(horizontalForce*5,player.linearVelocity.y)
}
fun cameraUpdate(delta:Float){
var position:Vector3 = camera.position
position.x = player.position.x * PPM // if you get box2d units multiply with ppm
position.y = player.position.y * PPM
camera.position.set(position)
camera.update()
}
fun createBox(x:Float,y:Float,width:Int,height:Int,isStatic:Boolean):Body{
var pBody:Body
var def:BodyDef
def = BodyDef()
if(isStatic){
def.type = BodyDef.BodyType.StaticBody
}
else{
def.type = BodyDef.BodyType.DynamicBody
}
def.position.set(x/PPM,y/PPM)
def.fixedRotation = true
pBody = world.createBody(def)
var shape:PolygonShape = PolygonShape()
shape.setAsBox(width/2/PPM,height/2/PPM) // takes from center this is 32x32 box
pBody.createFixture(shape,1.0f)
shape.dispose()//clean it
return pBody
}
}
使用box2d和你的代码都是正确的。
-9.81向上推动物体,向下推动物体9.81。
在World
构造函数中,您设置了世界的引力。
而重力是一种自然现象,通过这种现象,所有具有质量或能量的物质 - 包括行星,恒星,星系,甚至光 - 都被带向(或倾向于)彼此。
基本重力是物体相互吸引的力量。
因此,在地球上,引力是物体被吸引到地球中心的力。
在地球上,我们的重力为~9.81意味着所有物体将以~9.81 m /s²的力量拉到地球的中心。
最后是合乎逻辑的,如果引力是一个将物体拉下来的力量 - 重力会将物体推向上方。
在地球上,我们的重力为~9.81,重力不是〜-9.81。 如果是这样的话,我们都会在宇宙之外结束。