0

So I'm currently rotating a sprite based on a bool clockwise / counter clockwise function.

This is my coding for the moving of the ship based on this...

func movesprite(direction direction: rotationDirection) {

    // Moves sprite left or right dependent on rotation //
    let movespriteLeft = SKAction.moveByX(-100, y: 0,  duration: 1)
    let movespriteRight = SKAction.moveByX(100, y: 0, duration: 1)


    if sprite == (direction == .clockwise) {
        sprite.runAction(moveshipLeft)
    }

    else if sprite == (direction == .counterClockwise) {
        sprite.runAction(moveshipRight)
    }

}

Anyway this doesn't seem to work, at all. My ship does rotate clockwise or counterclockwise fine and compiler accepts this but it has no bearing on the movement on screen.

What's going wrong?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

1 Answers1

0

moveByX/Y moves your sprite based on the screen coordinates, not the position of your ship, so moving will always be based on the x or y axis. You need to incorporate some trig functions (sin and cos) on your moveby to get it to move in the path you want:

let movespriteLeft = SKAction.moveByX(-100 *  sin(ANGLE), y: -100 * -cos(ANGLE),  duration: 1)
let movespriteRight = SKAction.moveByX(100 * sin(ANGLE), y: 100 * -cos(ANGLE), duration: 1)

Where ANGLE is in a randian value from 0 to 2PI

You may have to play around with sin and cos a bit depending on your coordinate system

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
  • Okay so I've implemented the trig functions but the sprite still does not actually move on - it does continue to rotate around it's anchor point (which is what I want) but there is no movement about x/y axis? – Daniel Richardson Oct 19 '15 at 20:06
  • no movement at all? what does direction equal then – Knight0fDragon Oct 19 '15 at 20:11
  • sorry my code is wrong let me edit it – Knight0fDragon Oct 19 '15 at 20:12
  • It's a bool equivalent variable of essentially 1 = clockwise, 0 = counterclockwise. So to me logically it makes sense that I should be able to link these values to triggers for the SKActions? – Daniel Richardson Oct 19 '15 at 20:15
  • Rereading your question, I am now understanding your problem, I need to see more code, it seems to me that the sprite variable may not have a link to sprite on your screen, so the action you call may not be correct – Knight0fDragon Oct 19 '15 at 20:21
  • That is actually exactly what I've done - through messing with my code I'd stopped the function working entirely. Much needed nudge in the right direction haha – Daniel Richardson Oct 19 '15 at 20:28
  • @Knight0fDragon could you please assist me with this question https://stackoverflow.com/questions/44241484/how-to-limit-the-movement-of-two-anchored-lines-so-they-swing-continually-like-a – iGetIt May 30 '17 at 14:23