derrick56007 / SpriteKit-Joystick

Joystick class for Sprite Kit
32 stars 7 forks source link

Normalized Movement #2

Closed rickroll closed 10 years ago

rickroll commented 10 years ago

How would you suggest handling normalized movement? For example, I always want my character to move 5 pixels in whatever direction the joystick is in, I don't want speed changes at all.

I tried using this to get normalized x and y newX = cos(self.joystick.angularVelocity)) newY = sin(self.joystick.angularVelocity))

self.player.position = CGPointMake(self.player.position.x + 5 * newX, self.player.position.y + 5 * newY)

it works correctly as far as normalized speed, but always seems to be 90 degrees off. I'm working with a landscape game.

Thanks

derrick56007 commented 10 years ago

Inside the joystick implementation file

Replace:

        if (sqrtf(powf((touchPoint.x - self.anchorPointInPoints.x), 2) + powf((touchPoint.y - self.anchorPointInPoints.y), 2)) <= thumbNode.size.width)
        {
            CGPoint moveDifference = CGPointMake(touchPoint.x - self.anchorPointInPoints.x, touchPoint.y - self.anchorPointInPoints.y);

            thumbNode.position = CGPointMake(self.anchorPointInPoints.x + moveDifference.x, self.anchorPointInPoints.y + moveDifference.y);
        }
        else
        {
            double vX = touchPoint.x - self.anchorPointInPoints.x;
            double vY = touchPoint.y - self.anchorPointInPoints.y;
            double magV = sqrt(vX*vX + vY*vY);
            double aX = self.anchorPointInPoints.x + vX / magV * thumbNode.size.width;
            double aY = self.anchorPointInPoints.y + vY / magV * thumbNode.size.width;

            thumbNode.position = CGPointMake(aX, aY);
        }

With:

            double vX = touchPoint.x - self.anchorPointInPoints.x;
            double vY = touchPoint.y - self.anchorPointInPoints.y;
            double magV = sqrt(vX*vX + vY*vY);
            double aX = self.anchorPointInPoints.x + vX / magV * radius;
            double aY = self.anchorPointInPoints.y + vY / magV * radius;

            thumbNode.position = CGPointMake(aX, aY);

set the radius to what looks good for your use

(Yes, i know this is a hacky way, but it should work for now)

rickroll commented 10 years ago

Hey I actually figured it out. (swift version)

var newY = CGFloat(cos(self.joystick.angularVelocity * -1)) var newX = CGFloat(sin(self.joystick.angularVelocity * -1))

self.player.position = CGPointMake(self.player.position.x + 5 * newX, self.player.position.y + 5 * newY)