我迫切需要帮助。我已经花了3个小时拉我的头发,因为我不知道如何通过一个平台工作来解决我的问题!
我希望玩家能够在平台上跳跃,而不是在它上面出现故障,或者让它掉进去。但是,如果玩家举起左箭头键或右箭头键并与平台边缘接触,也会出现这种情况!我真的需要你的帮助,我可以将平台碰撞的简单方面与我的代码一起使用。
这是我的代码:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Form1 extends Applet implements Runnable, KeyListener
{
private Image dbImage;
private Graphics dbg;
Thread t1;
int x = 300;
int y = 300;
boolean jumping = false;
double yVel = 0;
double termVel = 10;
int loop_cnt = 0;
int start_cnt = loop_cnt;
boolean falling = false;
boolean left, right, up, down;
double counter2 = 4;
int counter;
int num = 7;
int prevY = y;
int prevX = x;
int d = 0;
Rectangle player;
Rectangle platform;
public void init()
{
setSize(600, 400);
}
public void start()
{
player = new Rectangle();
platform = new Rectangle();
addKeyListener(this);
t1 = new Thread(this);
t1.start();
}
public void stop()
{
}
public void destroy()
{
}
@Override
public void run()
{
while (true)
{
//this code will be used if the player is on a platform and then walks off it by pressing either right or left
if (y <= 300 && !up)
{
y += 10;
}
if (left)
{
prevX = x;
x -= 2;
}
if (right)
{
prevX = x;
x += 2;
}
if (up)
{
counter2 += 0.05;
prevY = y;
y = y + (int) ((Math.sin(counter2) + Math.cos(counter2)) * 5);
if (counter2 >= 7)
{
counter2 = 4;
up = false;
}
}
if (y >= 300)
{
falling = false;
y = 300;
}
repaint();
try
{
t1.sleep(17);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public Rectangle IntersectPlatform()
{
return platform;
}
public void update(Graphics g)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
// initialize buffer
if (dbImage == null)
{
}
// clear screen in background
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor(getForeground());
paint(dbg);
// draw image on the screen
g.drawImage(dbImage, 0, 0, this);
}
public void paint(Graphics g)
{
String string = String.valueOf(y);
g.setColor(Color.RED);
g.fillRect(x, y, 40, 100);
player.setBounds(x, y, 40, 100);
g.setColor(Color.BLUE);
platform.setBounds(180, 300, 100, 40);
g.fillRect(180, 300, 100, 40);
g.drawString(string, 100, 100);
}
@Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_UP:
up = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
}
}
@Override
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
down = false;
break;
}
}
@Override
public void keyTyped(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
}