I've got a bit of a conundrum here, and sadly my math (grade 11) isn't enough to help me get a clear idea of what I should fix here. Since angles lose their precision when moving based on pixels (ints) I almost always use a method similar to this:
This way, realXloc and realYloc keep track of the position (rather than getY() and getX()).
That all works fine and dandy, but now here is my next challenge.
I want to have the monster fire a shot in the direction of the player. To do this, I just have it add a new Shot() to the world, then let the "addedToWorld" of the shot do the calculating.
In the enemy's "addedToWorld", it calls the method "pointAtObject(character)" (character is the variable with the reference to the player).
the "angle =" part is the code from here to determine the angle. It normally uses setRotation(expression) instead of "angle =", but I think it's synonymous in this case.
now that I have the xMove and yMove variables, I've changed the moveDouble() method
But, as lovely as it can be, the shot moves in a straight line right or left.
When I tried "setRotation((int)(180*Math.atan2(target.getY()-getY(),target.getX()-getX())/Math.PI));" all was wonderful, only I lost the precision. Is there a way I can modify something to get that added "virtual pixel" precision? Also, I don't want the object rotating then moving based on rotation, I want to keep the object aligned but move at the specified angle. I'm reading the API move() method right now.
public void moveDouble() { realXloc = realXloc + xMomentum; realYloc = realYloc + yMomentum; setLocation((int)realXloc, (int)realYloc); }
public void pointAtObject(Actor target) { if(character != null) { angle = ((int)(180*Math.atan2(target.getY()-getY(),target.getX()-getX())/Math.PI)); //** This is a slightly modified version of the Move() function in the Greenfoor Actor API. All credit to them. double radians = Math.toRadians(angle); xMove = (Math.cos(radians)); yMove = (Math.sin(radians)); } }
public void moveDouble() { realXloc = realXloc + (xMove * xMomentum); // xMomentum and yMomentum are both 4 for test realYloc = realYloc + (yMove * yMomentum); setLocation((int)realXloc, (int)realYloc); }