日期:2014-05-20  浏览次数:20694 次

问问小球算法
我在wtk2.5包中看了sun公司提供的audioDemo的程序,其中有小球碰撞墙,然后在反弹的这种,程序中定义:
//   the   matrix   to   transform   the   direction   based   on   the
//   current   direction   and   which   wall   was   hit
static   int[][]   matrix   =   {   {   1,   -1,   -1,   1,   1,   1   },   {   -1,   -1,   1,   1,   -1,   1   },
null,   {   1,   1,   -1,   -1,   1,   -1   },   {   -1,   1,   1,   -1,   -1,   -1   }   };
小球运行:
public   void   run()
{
//   System.out.println( "starting...   "   +   this);
int   right   =   left   +   width;
int   bottom   =   top   +   height;

while   (!stop)
{
ballSize   =   radius   *   2;

//   calculate   a   direction   of   the   ball   as   an   integer   in   the   range
//   -2   ..   2   (excluding   0)
int   direction   =   deltaX   +   deltaY;

if   (direction   ==   0)
{
direction   =   deltaX   +   (2   *   deltaY);
}

//   is   the   current   position   colliding   with   any   wall
int   collision   =   0;

if   ((posX   <=   left)   ||   (posX   > =   right))
{
//collision++;---例子中的
this.deltaX=-this.deltaX;---我写的

}

if   ((posY   <=   top)   ||   (posY   > =   bottom))
{
//collision   +=   2;---例子中的
this.deltaY=-this.deltaY;---我写的
}

//   change   the   direction   appropriately   if   there   was   a   collision
if   (collision   !=   0)
{
try
{
javax.microedition.media.Manager.playTone(note,
100   /*   ms   */,   100);
}
catch   (Exception   ex)
{
System.out.println( "failed   to   play   tone ");
}

collision   =   (collision   -   1)   *   2;

deltaX   =   matrix[direction   +   2][collision];
deltaY   =   matrix[direction   +   2][collision   +   1];
}

//   calculate   the   new   position   and   queue   a   repaint

posX=posX+deltaX;
posY=posY+deltaY;

if   (doRepaint)
{
canvas.repaint();
}
我想问的是:这个矩阵matrix怎么定义出来的?
其实我只是改动一个地方,保证撞左右墙,X分速度取反,撞上下墙y速度取反,也实现了同样的功能,
例子的用意是什么呢?


------解决方案--------------------
我以前研究过。其实例子是用笨方法实现简单的功能。而且有迷惑大众的意思。我讨厌单纯是为了卖弄技术而卖弄技术的例子。

给你将一下吧。首先明确一点,例子中小球的运动方向只有4种,也就是左上,右上,左下,右下。其余的方向都没有,比如水平,垂直方向都没有。

每次
posX=posX+deltaX;
posY=posY+deltaY;
来改变位置。deltaX,deltaY可为+1也可为-1。

用direction作为一个方向的合成量代表四个方向,分别是-2,-1,1,2。但是它不能取0。
比如方向是左上,那么这时候deltaX = -1, deltaY = -1,则direction = -2,代表左上方向。
再举个例子,右上方向,这个时候deltaX = 1, deltaY = -1,
由 if (direction == 0) direction = deltaX + 2*deltaY; 这句,可以控制direction = -1。
同理,依次类推。

左上:direction = -2