我不明白为什么当我碰到我的物体时,我的角色会冻结。比如如果我碰撞碰撞()我可以左右移动,但不起来,如果我碰撞碰撞2()我冻结在所有地方,但是,如果我碰到我制造的界限我仍然可以四面八方没有问题。 xa和ya仍然设置为0.
package com.questkings.game;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Player{
int x = 1; // Location of player
int y = 314; // location of player
int xa = 0; // Representation of where the player goes
int ya = 0; // Representation of where the player goes
private int speed = 2;
int[] playerPos = {x, y};
private static final int WIDTH = 30;
private static final int HEIGHT = 30;
private Game game;
public Player(Game game){
this.game=game;
}
public void move(){
if(x + xa < 0) // Left Bounds
xa = 0;
else if (x + xa > game.getWidth() - WIDTH) // Right Bounds
xa = 0;
else if (y + ya < 0) // Top Bounds
ya = 0;
else if(y + ya > game.getHeight() - WIDTH)
ya = 0;
else if (collision()) // Tile bounds
ya = 0;
else if (collision2()){
ya = 0;
xa = 0;
}
x = x + xa;
y = y + ya;
}
// Method to find where player is located
public int[] Playerposition(){
return playerPos;
}
public void Gravity(){
}
public void paint(Graphics2D g2d){
//Draws player to screen
g2d.drawImage(getPlayerImg(), x, y, null);
}
public Image getPlayerImg(){
ImageIcon ic = new ImageIcon("C:/Users/AncientPandas/Desktop/KingsQuest/Misc/Images/Sprites/player.png");
return ic.getImage();
}
public void keyReleased(KeyEvent e){
xa = 0;
ya = 0;
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_S)
xa = -speed;
if (e.getKeyCode() == KeyEvent.VK_F)
xa = speed;
if (e.getKeyCode() == KeyEvent.VK_E)
ya = -speed;
if (e.getKeyCode() == KeyEvent.VK_D)
ya = speed;
}
public Rectangle getBoundsPlayer(){
return new Rectangle(x, y, WIDTH, HEIGHT);
}
private boolean collision(){
return game.maplayout.getBoundsBlock().intersects(getBoundsPlayer());
}
private boolean collision2(){
return game.maplayout.getBoundsBlock2().intersects(getBoundsPlayer());
}
}
答案 0 :(得分:0)
在我看来,如果collision()
返回true,则您的播放器将无法移动,因为ya
和xa
设置为零。这意味着一旦你击中某个东西,你就会被困在那里直到你没有击中它,这完全是你无法控制的。如果你碰撞的东西一动不动,你将永远无法逃脱。
我要做的是在移动后检查的碰撞:
// handle hitting sides like normal
x = x + xa;
y = y + ya;
// now that you've moved, check if you're colliding
if (collision()){
// if you have, go back to where you were
x = x - xa;
y = y - ya;
}
通过这种方式,你可以回到以前的位置,这应该是安全的,因为你以某种方式在没有碰撞的情况下到达那里。
我不确定你的碰撞逻辑是否可以解决这个问题,所以我唯一可以说的是,如果你发生碰撞,尝试将ya
和xa
乘以-1,这将是向你发送相反的方向,希望不受伤害。我们的想法是,朝着你想要的方向前进会让你陷入困境,所以相反的方向移动应该解决它。这样做的问题是,如果向后移动不会阻止你碰撞,那么你将再次反转方向,并且最有可能在你开始的地方结束,仍然会发生碰撞。这形成了一个无限循环,你的玩家最有可能看起来像是癫痫发作,但我看到很多游戏都发生了类似的物理错误。