0

I'm developing a game in AS3. There is a Weapon superclass, which contains methods such as shoot and reload, which will behave the same across all weapons.

The specific weapons, such as Pistol, Shotgun inherit from this class so they can use these methods. They have public static variables, such as what type of bullet to shoot, rate of fire, bullet spread, that make them unique, and are used in these methods. They need to be public static variables so I can look them up from somewhere else in the core when all I've got there is the type of weapon that was fired.

Is this how I should be trying to do it? How does the Weapon superclass access these variables?

4

1 回答 1

0
public static const RATE:uint = 2;

Weapon类可以通过 asWeapon.RATE或 as访问它RATE。当涉及到静态对象时,作用域的工作有点奇怪。我个人认为您不应该能够使用 just 访问静态对象RATE,但它确实有效。

子类继承静态属性和方法。它们完全属于创建它们的类(如果您知道静态对象的真正含义,这很有意义)。所以对于所有的类,甚至是扩展的类Weapon,你都必须public static通过Weapon.RATE.

然而,我注意到了一个奇怪的地方。如果您使用protected访问修饰符而不是public,类可以通过 访问其超类中的静态对象RATE,就好像它是在类本身中创建的一样。我不知道这背后的逻辑,但它确实有效。

所以:

public class Weapon {
    protected var RATE:uint = 2;
    public var RATE2:uint = 5;
}

public class Gun extends Weapon {
    trace( RATE ); // output 2
    trace( Weapon.RATE ); // output 2
    trace( RATE2 ); // output Error, access of undefined property
    trace( Weapon.RATE2 ); // output 5
}

编辑:回应第一条评论:

超类的工作方式是,扩展类的对象可以访问超类中的所有公共和受保护对象。

所以假设武器类是这样的:

public class Weapon {
    public function shoot():void{}
    protected function reload():void{}
    private function aim():void{}
}

您可以像在超类本身中一样访问子类中的这些方法:

public class Pistol extends Weapon{
    public function Pistol() {
        this.shoot(); // works
        this.reload(); // works
        this.aim(); // doesn't work because it is private
    }
}

现在,如果您希望进一步抽象事物,您可以在您的超类中使用 protected 或 public 修饰符设置属性,并为所有武器设置默认值。在您的超类方法中,您只需调用这些值。在子类中,您将它们更改为您需要的任何内容

public class Weapon {
    public var rate:uint = 2;

    public function shoot():void{
        // use this.rate here
    }
    protected function reload():void{}
    private function aim():void{}
}

public class Pistol extends Weapon{
    public function Pistol() {
        this.rate = 5; // value of rate is now 5 and will be used in shoot()
        this.shoot(); // works
        this.reload(); // works
        this.aim(); // doesn't work because it is private
    }
}
于 2013-10-17T17:51:13.563 回答