c# - 如何在游戏中拥有局部位置和全局位置

标签 c# recursion 2d

我有一个名为 Component 的基类。我还有 2 个接口(interface) I2DComponent 和 I3DComponent。我目前正在研究 I2DComponent。

实现:

/// <summary>
/// Represtions a 2D object. These objects will be drawn after 3D objects,
/// and will have modifiers automatically provided in the editor.
/// </summary>
public interface I2DComponent
{
    /// <summary>
    /// Gets or sets the rectangle.
    /// </summary>
    /// <value>The rectangle.</value>
    Rectangle Rectangle { get; set; }

    /// <summary>
    /// Gets the local position on the game screen.
    /// </summary>
    /// <value>The local position on the game screen.</value>
    /// <remarks>The rectangle position minus the parent screen position.</remarks>
    Rectangle LocalPosition { get; }

    /// <summary>
    /// Gets or sets the scale.
    /// </summary>
    /// <value>The scale.</value>
    float Scale { get; set; }
}

所以问题是我需要访问全局位置或 Rectangle 来检查鼠标是否在它上面。

if (component.Rectangle.Contains(mouse.Rectangle))
{
    do somthing.
}

但是当我只是访问并四处移动它时,我只想访问本地位置,这样如果我在位置 50、50 有一个游戏屏幕,那么我可以将本地位置设置为 0、0,它将是在父游戏屏幕的左上角。我想真正的问题是我不想通过说不小心设置 Rectangle

component.Rectangle = new Rectangle(component.Rectangle.X + 5, component.Rectangle.Y + 5, component.Rectangle.Width, component.Rectangle.Height);

这或多或少是一个访问器设计问题,我想让它看起来正确,但我在这样做时遇到了麻烦。

更新:

如果我改变它,使 I2D 组件只有 Bounds 和 scale,然后在 GameScreen 中有一个函数来获取组件的当前“全局”位置,会怎样。

更新:

这些 2D 对象都是绘制为不在 3D 空间中的 hud 或 gui 对象的对象。只是一个澄清。

更新:

我现在正在考虑以递归方式执行此操作,但我不确定我将如何执行此操作。

最佳答案

我只会担心修改游戏对象的本地位置,而不是屏幕位置,因为这取决于相机的位置和视口(viewport)。

有两种方法可以解决在屏幕上查找某物的位置的问题。第一种是使用获取相机的访问器方法,另一种是首先使用相机作为转换方法。我更喜欢后者,因此重写:

public interface I2DComponent
{
    /// <summary>
    /// Gets or sets the local (world) bounds of the object.
    /// </summary>
    /// <value>The rectangle.</value>
    Rectangle Bounds{ get; }

    /// <summary>
    /// Gets or sets the scale.
    /// </summary>
    /// <value>The scale.</value>
    float Scale { get; set; }
}

然后在camera中有两种方法

public class Camera
{
    public Rectangle WorldToScreen(Rectangle rect);
    public Rectangle ScreenToWorld(Rectangle point);
}

通过这种方式,您可以保留一个完全不关心屏幕的封装对象,以及一个处理所有转换的相机。

关于c# - 如何在游戏中拥有局部位置和全局位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1045219/

相关文章:

c# - Page.Validate 与 Page.IsValid

javascript:递归匿名函数?

c++ - 不了解此递归函数中的 return (C++)

java - 垂直于一点的 vector

javascript 跳跃字符不起作用

graphics - 2D 图像旋转,几个问题

c# - Prism : Change the active view

c# - 字典中用于检查键是否存在的逻辑

c# - 如果使用 SqlServer CE 4.0 执行代码优先,数据库的位置是什么?

c++:递归中的堆栈溢出错误