mardi 5 mai 2015

Centering the camera on the character

I am a beginner and I have started my first project. It should be a little game where you can run to the left and to the right. But I don't know how to set the camera settings.

I'd be very thankful if you could help me, tell me how I can improve my code and what is wrong.

Here is my Code:

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var ground:SKSpriteNode = SKSpriteNode()
var hero: MPCharacter!
var tree:MPTree!

override func didMoveToView(view: SKView) {

    backgroundColor = UIColor(red: 155.0/255.0, green: 201.0/255.0, blue: 244.0/255.0, alpha: 1.0)
    self.anchorPoint = CGPointMake(0.5, 0.5)

    // --> hero <--
    hero = MPCharacter()
    hero.position = CGPointMake(frame.size.width/2, view.frame.size.height/2)
    hero.zPosition = 100
    hero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(hero.size.width, hero.size.height))
    hero.physicsBody!.dynamic = true

    addChild(hero)

    // --> ground <--
    ground = SKSpriteNode(imageNamed: "ground")
    ground.size = CGSizeMake(frame.size.width, frame.size.height/3)
    ground.position = CGPointMake(frame.size.width/2, frame.size.height/2 - ground.size.height)

    ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(frame.size.width, ground.size.height - 25))
    ground.physicsBody!.dynamic = false

    addChild(ground)

    // --> Tree <--
    tree = MPTree()
    tree.position = CGPointMake(frame.size.width/2, ground.size.height + tree.size.height/3 - 10)
    tree.zPosition = 10

    tree.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(tree.size.width, tree.size.height - 10))
    tree.physicsBody!.dynamic = false

    addChild(tree)

    // --> Physics <--
    self.physicsWorld.gravity = CGVectorMake(0, -5.0)
    self.physicsWorld.contactDelegate = self

}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch:AnyObject in touches {

        let location = touch.locationInNode(self)

        if location.x < CGRectGetMidX(self.frame) {
            hero.physicsBody!.velocity = CGVectorMake(0, 0)
            hero.physicsBody!.applyImpulse(CGVectorMake(-5, 10))
        }
        else {
            hero.physicsBody!.velocity = CGVectorMake(0, 0)
            hero.physicsBody!.applyImpulse(CGVectorMake(5, 10))
        }
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire