我的 Player 类中的平台碰撞代码不起作用,有时会出现故障。我创建了不同的方法来应用重力等等。
当玩家在平台下跳跃时,我希望他们与平台底部碰撞并使用我创建的重力方法回落。
当玩家走进平台的两端时,我希望他们停在平台旁边。
我想始终确保玩家无法通过平台,这似乎是我的失败。
如果有人可以帮助我,我将不胜感激。
这是我的 Player 类,小程序屏幕大小为 600x400:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Player implements KeyListener
{
int x, y, width, height;
boolean jump, left, right;
PlayerThread playerThread;
int maxHeight = 40;
double heightC = 0;
boolean onPlatform = false;
boolean landed = true;
int prevY;
public Player()
{
x = 500;
y = 350;
width = 40;
height = 50;
playerThread = new PlayerThread();
playerThread.start();
}
public void paint(Graphics g)
{
String str = String.valueOf(x);
String str2 = String.valueOf(y);
g.setColor(Color.RED);
g.fillRect(x, y, width, height);
g.drawString("X: " + str + ", Y: " + str2, 100, 100);
}
public void update(Platform p)
{
CheckForCollision(p);
}
public void CheckForCollision(Platform p)
{
int pX = p.getX();
int pY = p.getY();
int pWidth = p.getWidth();
int pHeight = p.getHeight();
//THIS IS COLLISION DETECTION CODE THAT DOES NOT WORK
if (y + height > pY && y < pY + pHeight && x + width > pX && x < pX + pWidth)
{
y = prevY;
landed = true;
}
}
public class PlayerThread extends Thread implements Runnable
{
public void run()
{
while (true)
{
if (left)
{
x -= 2;
}
if (right)
{
x += 2;
}
if (jump)
{
if (heightC >= maxHeight)
{
System.out.println(heightC);
jump = false;
heightC = 0;
}
else
{
heightC += 1.5;
prevY = y;
y -= 5;
landed = false;
}
}
//GRAVITY CODE
if (!jump)
{
if (y < 400 - height && !landed)
{
prevY = y;
y += 5;
landed = false;
}
}
if (y >= 400 - height)
{
y = 400 - height;
landed = true;
}
try
{
sleep(17);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_SPACE:
if (landed)
{
jump = true;
}
break;
}
}
@Override
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_SPACE:
break;
}
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
public int getWidth()
{
return width;
}
public void setWidth(int width)
{
this.width = width;
}
public int getHeight()
{
return height;
}
public void setHeight(int height)
{
this.height = height;
}
@Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
}