如何向自定义对象添加方法

本文关键字:添加 方法 对象 自定义 | 更新日期: 2023-09-27 18:20:04

我正在制作一个游戏。我创建了一个名为"Player"的对象。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));

这是相当低效的。

我不知道这叫什么,也无法用谷歌搜索。请帮忙。谢谢

如何向自定义对象添加方法

有没有办法把它变成一个扩展对象的方法?

尝试

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

而不是

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

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

玩家等级:

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;