www.pudn.com > 50code.rar > BallSprite.java, change:2007-02-26,size:1817b


package demo; 
import javax.microedition.lcdui.Image; 
import javax.microedition.lcdui.game.Sprite; 
 
 
public class BallSprite extends Sprite{ 
	private int m_nSpeedX = 0;					//小球X方向的速度 
	private int m_nSpeedY = 0;					//小球Y方向的速度 
	public BallSprite( Image image, int frameWidth, int frameHeight){ 
		super(image, frameWidth, frameHeight);		 
		defineReferencePixel(frameWidth / 2, frameHeight / 2); 
	} 
	//设置小球的速度 
	public void setSpeed( int x, int y ){ 
		m_nSpeedX = x; 
		m_nSpeedY = y; 
	} 
	//增加小球的速率,注意速率和速度的区别 
	public void AddSpeed( int x, int y ){ 
		if( m_nSpeedX < 0 && m_nSpeedX - x < 0 ) 
			m_nSpeedX = m_nSpeedX - x; 
		else if( m_nSpeedX > 0 && m_nSpeedX + x > 0 ) 
			m_nSpeedX = m_nSpeedX + x; 
		if( m_nSpeedY < 0 && m_nSpeedY - y < 0 ) 
			m_nSpeedY = m_nSpeedY - y; 
		else if( m_nSpeedY > 0 && m_nSpeedY + y > 0 ) 
			m_nSpeedY = m_nSpeedY + y; 
	} 
	//小球反弹,参数bHorizontal为true表示横向反弹,否则纵向反弹 
	public void Reflect( boolean bHorizontal ){ 
		if( bHorizontal ) 
			m_nSpeedX = -m_nSpeedX; 
		else 
			m_nSpeedY = -m_nSpeedY; 
	} 
	//逻辑操作,控制小球的运动 
	public void Logic( int scrWidth, int scrHeight ){ 
		int x = getRefPixelX(); 
		int y = getRefPixelY(); 
		x += m_nSpeedX; 
		y += m_nSpeedY; 
		//如果小球运动到屏幕边缘,则需要反弹 
		if( x < this.getWidth()/2 ) 
		{//如果小球运动到屏幕左边 
			x = this.getWidth()/2; 
			Reflect(true); 
		} 
		else if( x > scrWidth - this.getWidth()/2 ) 
		{//如果小球运动到屏幕右边 
			x = scrWidth - this.getWidth()/2; 
			Reflect(true); 
		} 
		if( y < this.getHeight()/2 ) 
		{//如果小球运动到屏幕上边 
			y = this.getHeight()/2; 
			Reflect(false); 
		} 
		else if( y > scrHeight ) 
		{//如果小球运动到屏幕下边,则直接消失 
			setVisible(false); 
		} 
		setRefPixelPosition(x, y); 
	} 
}