我正在尝试从MainChar的Update函数访问Key的Update函数。这两个类都继承自Sprite类。在主字符中,我得到了错误:
非静态字段,方法或属性'Key.Update(GameTime,List)'需要一个对象引用。我尝试将类型放在参数之前,但出现错误:
'GameTime'是一种类型,在给定的上下文中无效,'Sprite'是一种类型,在给定的上下文中无效。
我还尝试通过执行以下操作来创建Key的新实例:关键码=新关键码(纹理,位置);我再次尝试将类型放在前面,但得到了:Key不包含采用4个参数的构造函数,并且在给定的上下文中无效。帮助将不胜感激。
此问题与一个类似的问题相关,该问题未能解决我的问题,因为我无法将Update或Key设为静态。
public MainChar(Texture2D texture) : base(texture)
{
Scale = 0.1f;
}
public override void Update(GameTime gameTime, List<Sprite> sprites)
{
Move();
foreach (var sprite in sprites)
{
if (sprite == this)
{
continue;
}
if (Velocity.X > 0 && IsTouchingLeft(sprite) || Velocity.X < 0 && IsTouchingRight(sprite))
{
Velocity.X = 0;
}
if (Velocity.Y > 0 && IsTouchingTop(sprite) || Velocity.Y < 0 && IsTouchingBottom(sprite))
{
Velocity.Y = 0;
}
if (sprite.rectangle.Intersects(rectangle))
{
hasDied = true;
}
if (sprite is Key)
{
Key.Update(gameTime, sprites);
}
}
Position += Velocity;
}
public int keyCount;
public Key(Texture2D texture, Vector2 position) : base(texture)
{
Position = position;
Scale = 0.08f;
}
public override void Update(GameTime gameTime, List<Sprite> sprites)
{
foreach (var sprite in sprites)
{
if (sprite is MainChar)
{
if (IsTouchingLeft(sprite) == true || IsTouchingRight(sprite) == true || IsTouchingTop(sprite) == true || IsTouchingBottom(sprite) == true)
{
Position = new Vector2(1000, 1000);
keyCount++;
}
}
}
}
在MainChar类的Update方法中,检查'sprite'是否为Key(if(sprite is Key)
)类型的对象之后,还需要强制转换'sprite'(这是对象of Sprite类型 )以键入Key,例如:((Key)sprite).Update(gameTime, sprites)
。
Sprite类可能没有可调用的Update方法-这就是为什么会出现错误的原因。 'is'检查不会自动将其强制转换为Key类型,因此,即使您知道'sprite'具有
cmhoequist的答案看起来不错,如果您使用的是支持版本,请尝试此操作
if (sprite is Key k)
{
k.Update(gameTime, sprites);
}