I have the classes AttackArea, Player and GameScene. I want to instantiate a new AttackArea object and place it near the Player, depending on the Players facing. Now I have problems with the right positioning. If I add the AttackArea as a child of GameScene, the positioning works as expected. But If I do that, the AttackArea isn't moving with the Player. Otherwise if I add the AttackArea as a child of the Player, it's moving with the Player. That's exactly what I want. The problem here is that the positioning of the AttackArea is now far away from the Player. This is the code in the Player class:
func attack(){
let attack = AttackArea(color: .red, size: CGSize(width: self.frame.width, height: self.frame.height / 2))
var animation = ""
switch playerFacing{
case .back:
attack.position = CGPoint(x: self.position.x, y: self.position.y + 40)
animation = Constants.Actions.playerAttackBack
case .front:
attack.position = CGPoint(x: self.position.x, y: self.position.y - 40)
animation = Constants.Actions.playerAttackFront
case .left:
attack.position = CGPoint(x: self.position.x - 40, y: self.position.y)
animation = Constants.Actions.playerAttackLeft
case .right:
attack.position = CGPoint(x: self.position.x + 40, y: self.position.y)
animation = Constants.Actions.playerAttackRight
case .none:
break
}
attack.zPosition = self.zPosition + 1
attack.setup()
if animation != ""{
self.run(SKAction(named: animation)!)
}
self.addChild(attack)
}
The first picture shows the situation when the AttackArea is a child of GameScene. The positioning is fine but I want it to be a child of Player.
The second picture shows the positioning when the AttackArea is a child of Player. The red square in the top right corner is the AttackArea and the red circle is the Player.
Why is the AttackArea so far away from the Player in this case? How can I archieve the same result as in the first picture with the only exception, that the AttackArea is child of the Player?
what happens if you change the positioning to
switch playerFacing{
case .back:
attack.position = CGPoint(x: 0, y: 0 + 40)
animation = Constants.Actions.playerAttackBack
case .front:
attack.position = CGPoint(x: 0, y: 0 - 40)
animation = Constants.Actions.playerAttackFront
case .left:
attack.position = CGPoint(x: 0 - 40, y: 0)
animation = Constants.Actions.playerAttackLeft
case .right:
attack.position = CGPoint(x: 0 + 40, y: 0)
animation = Constants.Actions.playerAttackRight
case .none:
break
}
I suspect that your player (for example) might be at pos 500, 500 and you are re-adding those values to the attack position so now it's position is 1000, 1040