如何在Swift中将SKSpriteNode添加到场景? [英] How to add a SKSpriteNode to the scene in Swift?

查看:93
本文介绍了如何在Swift中将SKSpriteNode添加到场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 SKSpriteNode 子类化为 GameObject ,我想实例化游戏场景类之外的对象。这是从 SKSpriteNode 派生的我的 GameObject 代码:

I tried to subclass SKSpriteNode into GameObject and I would like to instantiate objects outside the game scene class. Here is my GameObject code derived from SKSpriteNode:

import SpriteKit

public class GameObject: SKSpriteNode {

    init( texture: SKTexture?, color: UIColor, size: CGSize, position:CGPoint, name:String ) 
    {   
        objectSize = size;
        objectName = name;
        objectSprite = texture;
        //call superclass here
        super.init(texture: texture, color: color, size: size);
        self.position = position;
    }

    convenience init(_ _x:CGFloat, _ _y:CGFloat, _ _object:String )// Default initializer
    {
        let texture = SKTexture(imageNamed: _object);
        let position = CGPoint(x:_x, y:_y);
        self.init(  texture: texture,color: UIColor(),size: texture.size(), position: position, name: _object);
    }

    //Overloaded initializer with size as extra argument
    convenience init(_ _x:CGFloat, _ _y:CGFloat, _ _size:Int, _ _object:String)
    {
        //size for the SKSpriteNode.
        let texture = SKTexture(imageNamed: _object);
        let position = CGPoint(x:_x, y:_y);
        self.init(  texture: texture, color: UIColor(), size: CGSize(width: _size, height: _size),position: position, name: _object);
    }

要实例化从 GameObject派生的玩家,我必须写:

To instantiate a player derived from GameObject, I have to write:

let player = PlayerShip(100, 100, "PlayerShip")
addChild(player)

但是, addChild() gameScene 之外不起作用。我的目标是实例化 PlayerShip 类的项目符号,但我不知道如何实现。

However, addChild() does not work outside gameScene. My goal is to instantiate bullets from the PlayerShip class, but i can't figure out how. Does anyone have a suggestion?

推荐答案

如果您想在GameScene之外进行此操作,则需要一个go go属性,该属性具有参考GameScene。然后您可以调用:

If you want to do this outside of GameScene you need a kind go global property which has a reference to the GameScene. Then you can call:

myGameScene.AddChild(player)

这篇关于如何在Swift中将SKSpriteNode添加到场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆