-1

I am trying to make a simple top down car game and I am wondering if SpriteKit has a way to, simply, move an object based upon its current orientation?

I believe Scratch.com has a feature similar to this where you can move a sprite by its local coordinates or global coordinates. For example, if you have a sprite oriented to look at a corner of the screen, you can change its local x coordinate to move it towards that corner, or you can change its global x coordinate and shift it right.

Does SpriteKit have a similar feature? I want set the car's local velocity, but I can only figure out to set its global velocity. If I want to get the same effect by setting its global velocity, then I have to manipulate the dx and dy variables proportionally to the sprite's rotation, and that's a little more complicated than I wanted to do.

I have tried to move it by the global coordinates, but I would need to calculate the two dx and dy values to produce a vector that points in the direction the car is pointing.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Sam M
  • 1
  • 1
    Xcode is an IDE. Unless you are asking about Interface Builder, the GUI UX layout tool, "Xcode" does not have a coordinate system. MacOS and iOS use Quartz graphics, which has a nested coordinate system with global and local coordinates. So does UIKIt (iOS) and AppKit (Mac). There are also CALayers, which uses a slightly different nested coordinate system. – Duncan C Mar 30 '23 at 20:31
  • I am using SpriteKit for apps, how can I use the local coordinates? – Sam M Mar 31 '23 at 13:00
  • I have never used SpriteKit. You should edit your question so the title is "How do I use sprite-local coordinates in SpriteKit" since Xcode is not relevant. That way you'll catch the attention of people who know SpriteKit. – Duncan C Mar 31 '23 at 15:00
  • https://developer.apple.com/documentation/spritekit/sknode/about_spritekit_coordinate_systems and https://stackoverflow.com/questions/34076632/coordinate-system-in-spritekit – sangony Apr 01 '23 at 01:54

1 Answers1

0

You have two options:

1. Make the car a child of an SKNode

This way you can rotate the SKNode to whatever direction you want, and move your car in that direction by just doing car.position.x += someAmount. You wouldn't need to calculate your own dx and dy. The car's x-coordinate will basically correspond to the orientation of the SKNode.

2. Calculate it yourself (which isn't complicated to do)

I wrote you a simple function for this:

func move(_ sprite: SKSpriteNode, by amount: Double) {
    sprite.position.x += CGFloat(cos(sprite.zRotation)) * amount
    sprite.position.y += CGFloat(sin(sprite.zRotation)) * amount
}

From what I understand of your question, option 1 is your ideal solution.

halfer
  • 19,824
  • 17
  • 99
  • 186
rayaantaneja
  • 1,182
  • 7
  • 18