如何将方法添加到自定义对象

时间:2014-08-31 14:48:49

标签: c# object methods

我正在制作游戏。我有一个我创建的对象叫做“播放器”。 Player类看起来像这样:

public class Player
{
    public Vector2 pos;
    public Rectangle hitbox;
    public Rectangle leftHitbox;
    public Rectangle topHitbox;
    public Rectangle bottomHitbox;
    public Rectangle rightHitbox; 
    public Texture2D texture;
    public Vector2 speed;
    public bool canMoveLeft;
    public bool canMoveRight;
    public int vertSpeed;

    public Player(Vector2 position, Texture2D tex)
    {
        pos = position;
        texture = tex;
        speed = new Vector2(1, 1);
        vertSpeed = 0;
        hitbox = new Rectangle((int) position.X, (int) position.Y, tex.Width, tex.Height);
        leftHitbox = new Rectangle((int) pos.X, (int) pos.Y, 1, tex.Height);
        topHitbox = new Rectangle((int) pos.X, (int) pos.Y, tex.Width, 1);
        bottomHitbox = new Rectangle((int) pos.X, (int) (pos.Y + tex.Height), tex.Width, 1);
        rightHitbox = new Rectangle();
        canMoveLeft = true;
        canMoveRight = true;
        Debug.WriteLine("The texture height is {0} and the bottomHitbox Y is {1}", tex.Height, bottomHitbox.Y);
    }  

在游戏中,我使用我放在同一类中的这些方法移动播放器:

public static void MovePlayerToVector(Player player, Vector2 newPos)
{
    player.pos = newPos;
    UpdateHitboxes(player);
}

但是,正如您所看到的,该方法采用Player对象并更改pos变量。有没有办法将其变成扩展对象的方法? 例如,移动播放器将如下所示:

Player player = new Player(bla, bla);
player.MovePlayerToVector(new Vector2(1,1));

..而不是这个:

Player player = new Player(bla, bla);
Player.MovePlayerToVector(player, new Vector2(1,1));

..效率很低。

我不知道这叫什么,不能谷歌。请帮忙。感谢。

2 个答案:

答案 0 :(得分:2)

  

有没有办法将其变成扩展对象的方法?

尝试

public void MovePlayerToVector(Vector2 newPos)
{
    pos = newPos;
    UpdateHitboxes(this);
}

而不是

public static void MovePlayerToVector(Player player, Vector2 newPos)
{
    player.pos = newPos;
    UpdateHitboxes(player);
}

答案 1 :(得分:1)

使用实例方法而不是类方法,即

在玩家类中:

public void MoveToVector(Vector2 newPos)
{
    this.pos = newPos;
}

然后以下工作没有副作用。

Player player = new Player(bla, bla);
player.MoveToVector(new Vector2(1,1));

此外:

public Vector2 pos;
public Rectangle hitbox;

将这些设为私有,并使用方法或属性进行封装,例如

private Vector2 pos;
private Rectangle hitbox;