0

我在 Objective C 中有两个使用 cocos2D 的主要类,DebugZoneLayer 和 HeroClass。使用 Cocos2D 可能不是问题的一部分。

HeroClass 包含一个 CGPoint 和一个属性。我在 DebugZoneLayer 中有一个 HeroClass 的实例,初始化为hero = [[HeroClass alloc] init];

缩短了我的 HeroClass.h 以向您展示我如何创建 CGPoint vel。

@interface HeroClass : CCLayer {
    @public CGPoint _vel;
}

@property(assign) CGPoint vel;

在 HeroClass.m 中,我合成了我的属性,例如@synthesize vel = _vel;

在 DebugZoneLayer.m 中,我可以很好地引用我的 hero.vel x 或 y,但是任何为 hero.vel x 或 y 赋值的东西都会返回错误:Lvalue required as left operand of assignment

4

2 回答 2

1

以不同的方式重述 Chuck 完全正确的答案。

您的问题是 CGPoints 不是 Objective-c 对象,它们是 C 结构。您的属性 *_vel* 不是对象的实例,例如 NSArray、NSArray 或 DebugZoneLayer。

作为一个简单而懒惰的例子,使用 int 而不是 struct 和一些伪代码..

@interface HeroClass : CCLayer {
    int _numberOfLives;
}
@end

@implementation HeroClass
- (id)init {
    [super init];
    _numberOfLives = 3;
}

- (int)livesRemaining {
    return _numberOfLives;
}
@end

你不能像这样设置 _numberOfLives 的值..

foo = [[HeroClass alloc] init];
bar = [foo livesRemaining];
bar = 2;

更改bar的值不会更改 foo 的_numberOfLives实例变量的值,因为当您调用-livesRemaining时,bar被设置为_numberOfLives的当前值的副本。

简而言之,您需要学习一些 C.

于 2011-05-02T21:20:49.677 回答
1

没错——你不能那样做。属性只是一个方法调用,Objective-C 中的方法总是按值返回,这意味着返回的 CGPoint 只是一个临时 CGPoint,与对象中的值相同。不允许设置此临时值的组成部分。您需要在类上为点的 X 和 Y 值创建特殊的设置器,或者一次设置整个点。

于 2011-05-02T20:40:55.967 回答