【问题标题】:How to add methods to custom object如何向自定义对象添加方法
【发布时间】:2014-10-24 22:20:23
【问题描述】:

我正在制作游戏。我创建了一个名为“播放器”的对象。 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);
    }  

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

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));

.. 效率很低。

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

【问题讨论】:

    标签: c# object methods


    【解决方案1】:

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

    试试

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

    而不是

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

    【讨论】:

      【解决方案2】:

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

      在播放器类中:

      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;
      

      【讨论】:

      • 我会在 10 分钟内标记为答案,网站给我带来了问题 :( 感谢您的快速回复!
      猜你喜欢
      • 2011-09-10
      • 2011-06-09
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 2015-07-31
      • 2022-12-06
      相关资源
      最近更新 更多