
我到处找这本书的答案。我知道其他人读过这本书的感觉也是一样的。它被称为“为邪恶天才制作视频游戏”,有没有人读过这本书?我在项目10:激进赛车-赛车。所有的编译都是正确的,但出于某种原因,我的汽车并没有出现在JFrame上的正确位置。他们应该在两条白线下出现。我确信代码和书中的代码完全一样,但是这本书错了。我已经试过改变起点的高度部分,但不管我做什么,都不会让步。我不能附加一个图像,因为我没有代表至少10 .This是代码,处理汽车的位置。
public class TheCars extends JFrame
{
final int WIDTH = 900; int HEIGHT = 650;
double p1Speed = .5, p2Speed = .5;
Rectangle p1 = new Rectangle(WIDTH/9,HEIGHT/2, WIDTH/30,WIDTH/30);
Rectangle p2 = new Rectangle(((WIDTH/9)+((int)((WIDTH/9)*1.5)/2)),(HEIGHT/2)+
(HEIGHT/10),WIDTH/30,WIDTH/30);
//the constructor
public TheCars()
{
//the following code creates the JFrame
super("Radical Racing");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
//start the inner class (which works on it's own because it is a thread)
Move1 m1 = new Move1();
Move2 m2 = new Move2();
m1.start();
m2.start();
}
//this will draw the cars and the racetrack
public void paint(Graphics g)
{
super.paint(g);
//set the color to blue for p1
g.setColor(Color.BLUE);
//now draw the actual player
g.fill3DRect(p1.x,p1.width,p1.width,p1.height,true);
//set the color to red for p2
g.setColor(Color.red);
//now draw the actual player
g.fill3DRect(p2.x,p2.width,p2.width,p2.height,true);
}
private class Move1 extends Thread
{
public void run()
//This should all be in an infinite loop so that the process repeats.
{
while(true)
{
//now put in the try block. This will let
//the program exit if there is an error
try
{
//first refresh the screen
repaint();
//increase speed a bit
if(p1Speed<=5)
p1Speed+=.2;
p1.y-=p1Speed;
//this delays the refresh rate
Thread.sleep(75);
}
catch(Exception e)
{
//if there is an exception (an error), exit the loop
break;
}
}
}
}
private class Move2 extends Thread
{
public void run()
{
//this should all be in an infinite loop so the process repeats
while(true)
{
//now put the code in a "try" block.
//this will let the program exit if there is an error
try
{
//first refresh the screen
repaint();
//increase the speed a bit
if(p2Speed<=5)
p2Speed+=.2;
p2.y-=p2Speed;
//this delays the refresh rate
Thread.sleep(75);
}
catch(Exception e)
{
//if there is an exception (an error), exitthe loop
break;
}
}
}
}
public static void main(String[]args)
{
new TheCars();
}
}发布于 2012-05-19 00:52:24
假设您要将这些Rectangle对象直接绘制到屏幕上,我们必须假设表达式"HEIGHT/2“和"HEIGHT/2 + HEIGHT/10”的结果是相等的,而且不是零,但很小。如果高度是一个int,并且值大于2,小于10,那么情况就是这样。这些框至少需要几百个才能显示在屏幕中间。检查HEIGHT的值(只使用System.out.println()就可以了),并确保它是窗口的实际高度。
编辑
现在我们看到了代码的其余部分:每次调用fill3DRect()的第二个参数都是错误的。它应该是y对象的Rectangle成员,它是一个大的、变化的数字,但是您传递的是width成员,这是一个固定的小数目。将两个调用都改为如下所示,您将回到轨道上:
g.fill3DRect(p1.x, p1.y, p1.width, p1.height, true);https://stackoverflow.com/questions/10661388
复制相似问题