Joystick example problem for android 2D
- by iQue
I've searched all over the web for an answer to this, and there are simular topics but nothing works for me, and I have no Idea why. I just want to move my sprite using a joystick, since I'm useless at math when it comes to angles etc I used an example, Ill post the code here:
public float initx = 50; //og 425;
public float inity = 300; //og 267;
public Point _touchingPoint = new Point(50, 300); //og(425, 267);
public Point _pointerPosition = new Point(100, 170);
private Boolean _dragging = false;
private MotionEvent lastEvent;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event == null && lastEvent == null) {
return _dragging;
} else if (event == null && lastEvent != null) {
event = lastEvent;
} else {
lastEvent = event;
}
// drag drop
if (event.getAction() == MotionEvent.ACTION_DOWN) {
_dragging = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
_dragging = false;
}
if (_dragging) {
// get the pos
_touchingPoint.x = (int) event.getX();
_touchingPoint.y = (int) event.getY();
// bound to a box
if (_touchingPoint.x < 25) {
_touchingPoint.x = 25; //og 400
}
if (_touchingPoint.x > 75) {
_touchingPoint.x = 75; //og 450
}
if (_touchingPoint.y < 275) {
_touchingPoint.y = 275; //og 240
}
if (_touchingPoint.y > 325) {
_touchingPoint.y = 325; //og 290
}
// get the angle
double angle = Math.atan2(_touchingPoint.y - inity,
_touchingPoint.x - initx) / (Math.PI / 180);
// Move the beetle in proportion to how far
// the joystick is dragged from its center
_pointerPosition.y += Math.sin(angle * (Math.PI / 180))
* (_touchingPoint.x / 70);
_pointerPosition.x += Math.cos(angle * (Math.PI / 180))
* (_touchingPoint.x / 70);
// stop the sprite from goin thru
if (_pointerPosition.x + happy.getWidth() >= getWidth()) {
_pointerPosition.x = getWidth() - happy.getWidth();
}
if (_pointerPosition.x < 0) {
_pointerPosition.x = 0;
}
if (_pointerPosition.y + happy.getHeight() >= getHeight()) {
_pointerPosition.y = getHeight() - happy.getHeight();
}
if (_pointerPosition.y < 0) {
_pointerPosition.y = 0;
}
}
public void render(Canvas canvas) {
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(joystick.get_joystickBg(), initx-45, inity-45, null);
canvas.drawBitmap(happy, _pointerPosition.x, _pointerPosition.y, null);
canvas.drawBitmap(joystick.get_joystick(), _touchingPoint.x - 26,
_touchingPoint.y - 26, null);
}
public void update() {
this.onTouchEvent(null);
}
og= original position.
as you can see Im trying to move the joystick, but when I do it stops working correctly, I mean it still works like a joystick but the sprite dosnt move accordingly, if I for example push the joystick down, the sprite moves up, and if I push it up it moves left.
can anyone PLEASE help me, I've been stuck here for sooo long and its really frustrating.