⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ballsprite.java

📁 J2ME编程的50个例子,适合掌上系统的编程
💻 JAVA
字号:
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);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -