Game Development Community

8 direction top-down style movement

by David Baerg · in Torque 2D Beginner · 05/10/2013 (5:30 am) · 4 replies

I am very new to torque 2d, I have had some previous experience with TGEA, but never TGB. I am wondering how to implement simple 8 direction movement like in Zelda using the physics system.

My current code looks like this:
...

function PlayerSprite::startMove(%this, %direction)
{
    %this.isDown[%direction]=true;
    %this.accelerate();
}
function PlayerSprite::stopMove(%this, %direction)
{
    %this.isDown[%direction]=false;
}

function PlayerSprite::accelerate(%this)
{
    for(%i=0;%i<4;%i++)
    {
        if(%this.isDown[%i])
        {
            %dir=Vector2Direction(90*%i,35);
            %this.applyLinearImpulse(%dir, "0 0");
        }
    }
    
    %this.moveschedule = %this.schedule(250,accelerate);
}

With the startMove and stopMove functions bound to WASD keys. But this causes the player to move twice as fast diagonally as horizontally or vertically. This could probably be fixed by interpreting the combination of certain keys as a direction, but I don't know how to do that without some really ugly if or switch statements. Also only accelerating to a certain max velocity would be useful too. So any guidance would be greatly appreciated :)

About the author

Recent Threads

  • Weird GUI Glitch...

  • #1
    05/10/2013 (6:01 am)
    Why not a single, simple if statement to check if you are already accelerating in the startMove method? If you are already accelerating, do not call accelerate. That's not ugly. It's simple and fastest solution.
    #2
    05/10/2013 (6:19 am)
    That wouldn't work, because then you could only move in one direction at a time
    #3
    05/10/2013 (6:24 am)
    Create your vector, normalize it and then multiply it by your desired scalar speed.
    #4
    05/10/2013 (6:56 am)
    Ah sorry, hadn't had my coffee yet so I missed some of the point. Go with Richard's suggestion.