Reputation: 51
So I have a character on a screen and I want it to be at the current mouse coordinates.
The problem I'm having is when the mouse is not on the screen the character will jump to some random location on the screen when what I want it to do is stay in the location the mouse was last in when it was on the screen.
Question:
How do I make it so my character stays in the last location the mouse was in on the screen?
import flash.ui.Mouse;
import flash.display.MovieClip;
import flash.events.*;
stage.addEventListener (Event.ENTER_FRAME,gameloop);
function gameloop(e:Event){
Mouse.hide();
Character.x = mouseX;
Character.y = mouseY;
}
Upvotes: 1
Views: 502
Reputation: 51
So what was happening is when the mouse left the screen it would for some reason read the mouse values in a seemingly random spot on the screen. The new random location of the mouse seemed to always be 60-70+ or so pixels away from the last mouse value so my solution was this:
stage.addEventListener(MouseEvent.MOUSE_MOVE,screenExit);
function screenExit(e:MouseEvent){
if((mouseX > (lastX+50))||(mouseX < (lastX-50))){
lastX =mouseX;
lastY =mouseY;
}
else if((mouseY > (lastY+50))||(mouseY < (lastY-50))){
lastX =mouseX;
lastY =mouseY;
}
else{
Character.x = mouseX;
Character.y = mouseY;
}
lastX =mouseX;
lastY =mouseY;
trace(mouseX, mouseY);
}
whenever the mouse moves it will check the values of the mouse, if the values are drastically different (50) then it assumes the mouse is off the screen (which it is) and does not update the characters location until the mouse returns to the screen and it can track movement again.
also it is possible for someone to move the mouse faster than 50 pixels (in which case it will lag for the next movement) but given the game I am making going that fast would be unlikely.
Upvotes: 1
Reputation: 14406
You just have to put some conditions on your position assignments:
function gameloop(e:Event){
Mouse.hide();
if(mouseX > 0 && mouseX < stage.stageWidth - Character.width){
Character.x = mouseX;
}
if(mouseY > 0 && mouseY < stage.stageHeight - Character.height){
Character.y = mouseY;
}
}
There you are saying, only update the characters x
value if the mouse position if greater than 0
and less than stage width (less the characters width which is helpful if you anchor point is 0,0 on your character). If the condition doesn't pass, the character will remain in it's previous position.
Your condition may be different depending on the bounds your characters needs to adhere to.
Though, if your mouse is off-screen (outside your application window), it should not update the mouseX/Y values at all, so perhaps there is another issue at play here?
Upvotes: 1