我是java和游戏编程的新手,我开始了我的第一个大型项目,这是一个2D平台益智游戏。 这是我的玩家动作代码
if (speedX > 0 && centerX <= 400){
centerX += speedX;
}
if (speedX < 0 && centerX >= 400){
centerX += speedX;
}
if (speedX > 0 && centerX >= 400){
bg1.setSpeedX(-MOVESPEED);
bg2.setSpeedX(-MOVESPEED);
}
if (speedX < 0 && centerX <= 400){
bg1.setSpeedX(MOVESPEED);
bg2.setSpeedX(MOVESPEED);
}
if (speedX == 0){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
if(movingRight == true && movingLeft == true ){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
// Handles Jumping
if (jumped == true) {
speedY += 1;
}
// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) {
centerX = 61;
}
rect.setRect(centerX - 47, centerY - 65, 32, 87);
centerY += speedY;
}
public void moveRight() {
speedX = MOVESPEED;
}
public void moveLeft() {
speedX = -MOVESPEED;
}
public void stopRight() {
movingRight = false;
stop();
}
public void stopLeft() {
movingLeft = false;
stop();
}
private void stop() {
if (movingRight == false && movingLeft == false) {
speedX = 0;
}
if (movingRight == false && movingLeft == true) {
moveLeft();
}
if (movingRight == true && movingLeft == false) {
moveRight();
}
}
public void jump() {
if (jumped == false) {
speedY = JUMPSPEED;
jumped = true;
}
}
这是碰撞代码
public void checkCollision(Rectangle rect){
if (rect.intersects(r)){
if(Player.movingRight){
Player.centerX = tileX + 11;
Player.speedX =0;
}
if(Player.movingLeft){
Player.centerX = tileX + 89;
Player.speedX = 0;
}
if(Player.speedY > 0){
Player.centerY = tileY - 25;
Player.speedY = 0;
Player.jumped = false;
}
}
}
有两个问题。第一个是如果我在登陆角色时按下其中一个移动键&#34;传送&#34;向右或向左。 我知道发生这种情况是因为我编程了如果角色与地面相交而moveRight或movingLeft是真的他向右或向左移动。(我这样做,所以水平碰撞会起作用)我想不出任何其他方式做它或如何解决它。
第二个问题是,如果角色移动平台,他就不会摔倒。 我尝试通过添加碰撞方法来修复它
else{
speedY += 1;
}
但它让角色因某种原因消失了。
非常感谢!
答案 0 :(得分:0)
此代码最初是用C ++编写的,用于3D平台游戏。我重写了它,但可能有一些错误。如果难以理解,我可以稍后画一幅画。
public void checkCollision(Rectangle rect){
if(player.intersects(rect)) {
//the rectangles intersect, time to move the player out of the block
if(rect.y+rect.height >= player.y && rect.y+rect.height-0.7f < player.y) { //if the player is at most 0.7 units (you should change this!) below top side
player.y = rect.y+rect.height; //set player to stand on top
speed.y = 0f; //stop the movement
onGround = true;
} else if(rect.y+rect.height > player.y && rect.y < player.y+player.height) { //if the playeer is on the side, but not below
float xEscMinus = (float)Math.abs((rect.x+rect.width)-player.x); //find the distance to the side
float xEscPlus = (float)Math.abs(rect.x-(player.x+player.width));
if(xEscMinus<xEscPlus) {
player.x = rect.x+rect.width;
} else {
player.x = rect.x-player.width;
}
}
}
}