-2

I've stripped this issue down to an image on a ZStack. The image should be in the lower left corner of the ZStack. When the .rotation for the image is modified, the location changes as if the underlying ZStack was rotated.

Here's the code:

import SwiftUI

let gridSize: Int = 20
let cellSize: Int = 30

struct MazeView: View {
  // what cell is the player in -- start lower left
  @State var playerCell: (Int, Int)? = (gridSize - 1, 0)

  var body: some View {
    ZStack {
      // player icon
      Image("Character center")
        .resizable()
        .frame(width: CGFloat(cellSize - 2), height: CGFloat(cellSize - 2))
        .position(playerPosition())
        .rotationEffect(.degrees(180)) // <- change this to mults of 90
    } // ZStack - the maze
      .frame(width: CGFloat(gridSize * cellSize), height: CGFloat(gridSize * cellSize))
      .border(Color.black)
  } // body

  private func playerPosition() -> CGPoint {
    if let current = playerCell {
      return CGPoint(x: (cellSize * current.1) + cellSize/2,
                                 y: (cellSize * current.0) + cellSize/2)
      } else {
         return CGPoint(x: cellSize/2, y: gridSize * cellSize + cellSize/2)
      }
    }
  }
}
3
  • The order of modifiers is important. Make sure you perform the rotation before applying any kind of offset or padding. Commented Nov 6 at 8:29
  • Please provide a minimal reproducible example, and that means not just providing code, but also clearly describing the desired behaviour and the actual behaviour. Commented Nov 7 at 11:06
  • Now that you have added the code to the question, it can be seen that .rotationEffect is being applied after .position. Try changing the order of these two modifiers. Commented Nov 7 at 12:28

2 Answers 2

1

As  Benzy Neez says in their comment, order of operations matters with rotations and translations. If you translate first, you move the center of rotation.

You should try rotating first, then translating. You might even have to move the position to the center of the image, rotate, move back, and then translate to your final position.

Sign up to request clarification or add additional context in comments.

Comments

0

Thank you all for your help. I'm relatively new to Swift, and so didn't understand that the order of modifiers mattered.

As suggested, I rotated before positioning and it now works as intended. It looks like I need some study on the topic of modifers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.