Getting movement going on a vector, then stopping it

Hey all :slight_smile: I’m working on a game involving telling a bug where to go and what to do when it gets there. Just started, focusing on getting the bug to move right now. To do that, I’m using a vector formula so it goes in straight lines.

Having a couple of issues, though. The first is getting the bug to follow the vector from its starting point to where the user clicks the mouse. The bug points itself in the right direction, and even scoots a little that way, but then it just stops. Repeated clicking causes it to scoot a little further along each time, but it doesn’t just walk over there.

To attempt to fix this, I created a setInterval that runs my vectory formula every 100 ms, to try and give it as smooth a transition as possible. I realize that’s rather resource intensive though, but I’m unaware of a better way of doing it. How should I code this so it’s smooth yet not resource intensive? I see a lot of people using onEnterFrame, but I’ve heard that’s a rather poor way of running things for game design. Is that true?

The second issue is in actually getting the bug to stop moving. I have a simple if checking if the bug’s coordinates are equal to the coordinates of the user’s mouse click, but the vector is imprecise as best and the bug frequently misses its exact destination, causing it to continue scurrying off the screen. What would be the best way to get the bug to stop moving?

Here is all of my code so far. If you’d like, I can also upload the FLA.


var moveX:Number = 0;
var moveY:Number = 0;
var moveAng:Number = 0;
var dirX:Number = 0;
var dirY:Number = 0;
var distX:Number = 0;
var distY:Number = 0;
var bugSpeed:Number = 100;
var moving:Boolean = false;
var tick:Number = 100;
var vectIntrvl:Number;
watchMouse = new Object();
Mouse.addListener(watchMouse);

attachStuff();

function attachStuff()
{
    _root.attachMovie("bug_mc", "bug_mc", _root.getNextHighestDepth(), {_x: Stage.width/2, _y: Stage.height/2});
}

watchMouse.onMouseUp = function()
{
    if(moving)
    {
        clearInterval(vectIntrvl);
        moving = false;
    }
    
    moveX = _xmouse;
    moveY = _ymouse;
    moving = true;
    
    findAngle();
}

function findAngle()
{
    distX = bug_mc._x - moveX;
    distY = bug_mc._y - moveY;
    
    bug_mc._rotation = -Math.atan2(distX, distY)/(Math.PI/180);
    
    vectIntrvl = setInterval(vector, tick);
}

function vector()
{    
    if(moving)
    {
        moveAng = bug_mc._rotation - 90;
        
        bug_mc.dirX = Math.cos(moveAng * Math.PI / 180) * bugSpeed;
        bug_mc.dirY = Math.sin(moveAng * Math.PI / 180) * bugSpeed;
        bug_mc._x += bug_mc.dirX / 50;
        bug_mc._y += bug_mc.dirY / 50;
    }
    
    if(bug_mc._x != moveX && bug_mc._y != moveY)
    {
        bug_mc.gotoAndPlay(1);
    }else{
        bug_mc.gotoAndStop(1);
        moving = false;
        clearInterval(vectIntrvl);
    }
}