【WiEngine 游戏引擎】基础(3)给游戏增加虚拟摇杆

WiEngine中自带了一个虚拟摇杆的实现--VirtualJoystick类

在Wiengine中给游戏添加虚拟摇杆非常方便,下面是具体实现代码:

public class VirtualButtonLayer extends Layer implements IVirtualJoystickCallback
{
	private static final int	CENTER		= -1;
	private static final int	NORTH		= 0;
	private static final int	NORTH_EAST	= 1;
	private static final int	EAST		= 2;
	private static final int	SOUTH_EAST	= 3;
	private static final int	SOUTH		= 4;
	private static final int	SOUTH_WEST	= 5;
	private static final int	WEST		= 6;
	private static final int	NORTH_WEST	= 7;
	// 当前的方向
	private int					mDir;
	private Label				mLabel;

	public VirtualButtonLayer()
	{
		mDir = CENTER;
		// 创建一个虚拟摇杆
		Sprite bg = Sprite.make(R.drawable.joystick_bg);
		bg.setDither(true);
		Sprite rocker = Sprite.make(R.drawable.joystick_rocker);
		VirtualJoystick vj = VirtualJoystick.make(bg, rocker);
		vj.setAnchor(0, 0);
		vj.setEventStyle(VirtualJoystick.VJS_NINE_DIRECTIONS);// 设置为9个方向
		vj.setPosition(DP(20), DP(20));
		vj.setCallback(this);
		addChild(vj);

		WYSize s = Director.getInstance().getWindowSize();
		// 添加一个Label,参数依次为 String 文字 ,float 字体大小
		mLabel = Label.make("当前方向:", 20);
		mLabel.setPosition(s.width / 2, s.height / 2);
		addChild(mLabel);
	}

	private float DP(float v)
	{
		return ResolutionIndependent.resolveDp(v);
	}

	@Override
	public void onVJDirectionChanged(int vjPointer, int newDirection)
	{
		switch (newDirection)
		{
			case VirtualJoystick.VJD_CENTER:
				mDir = CENTER;
				break;
			case VirtualJoystick.VJD_NORTH:
				mDir = NORTH;
				break;
			case VirtualJoystick.VJD_NORTH_EAST:
				mDir = NORTH_EAST;
				break;
			case VirtualJoystick.VJD_EAST:
				mDir = EAST;
				break;
			case VirtualJoystick.VJD_SOUTH_EAST:
				mDir = SOUTH_EAST;
				break;
			case VirtualJoystick.VJD_SOUTH:
				mDir = SOUTH;
				break;
			case VirtualJoystick.VJD_SOUTH_WEST:
				mDir = SOUTH_WEST;
				break;
			case VirtualJoystick.VJD_WEST:
				mDir = WEST;
				break;
			case VirtualJoystick.VJD_NORTH_WEST:
				mDir = NORTH_WEST;
				break;
		}
		mLabel.setText("当前方向:" + mDir);
	}

	@Override
	public void onVJNavigationEnded(int vjPointer)
	{
	}

	@Override
	public void onVJNavigationStarted(int vjPointer)
	{
	}
}


通过setEventStyle()设置摇杆类型,摇杆的类型有3个:



上面用到的Label也是nodes的子类,可以直接添加到Layer中。

最后是效果图:



转载请注明出处:http://blog.csdn.net/Vestigge





你可能感兴趣的:(游戏)