문제

I have two spriteNodes hero and the enemy, both with rectangular physicsBody applied. In the update, when the hero gets to the certain point, e.g hero.position.y <= 300 I want the enemy to rotate and face the the hero as it moves down.

the only sample code I found was the Adventure from Apple which has a faceTo class but I found it very complicated to use. I am looking for a nice and clean solution for it.

Thanks in advance.

도움이 되었습니까?

해결책

The most basic implementation should look something like this:

- (void)rotateNode:(SKNode *)nodeA toFaceNode:(SKNode *)nodeB {

    CGFloat angle = atan2f(nodeB.position.y - nodeA.position.y, nodeB.position.x - nodeA.position.x);

    if (nodeA.zRotation < 0) {
        nodeA.zRotation = nodeA.zRotation + M_PI * 2;
    }

    [nodeA runAction:[SKAction rotateToAngle:angle duration:0]];
}

It's important that you understand what is happening. Look up and read about atan2 (http://en.wikipedia.org/wiki/Atan2) and try to understand how the code above works.

다른 팁

You can use the xScale property of SKNode to make the sprite face the other way. This can be done by setting:

sprite.xScale = -1.0;

However, this has been proved to cause problems with the physicsBody, as can be seen from this question:

Flipped x-scale breaks collision handling (SpriteKit 7.1)

The solution for this problem is given there itself by JKallio.

He suggests keeping your sprite as a child of another SKNode (to which you apply the physicsBody) and changing the xScale property of the child node where needed. This is what I am using in my own project as well.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top