简体   繁体   English

如何访问主表单的成员

[英]How can I access member of main form

I am only learning C# and I am trying to make a 2D game.我只学习 C#,我正在尝试制作 2D 游戏。 I am at the stage where I have my Form1 set up with a 'PictureBox' for the player and the start of a player class:我正处于为我的 Form1 设置播放器的“PictureBox”和播放器类的开始阶段:

class Player
{
    private string _name;
    private int _health;

    internal Player(string name, int health = 100)
    {
        _name = name;
        _health = health;
    }

    int X = 0;

    internal void Draw()
    {
        updateInput();

        Draw();
    }

    internal void updateInput()
    {
        if(Keyboard.IsKeyDown(Key.Right))
            X = 1;
        else if (Keyboard.IsKeyDown(Key.Left))
            X = -1;
        else
            X = 0; 
    }
}

There is a PictureBox "pb_play" which contains the character's sprite on the main form.有一个 PictureBox "pb_play",它在主窗体上包含角色的精灵。 I tried setting its access modifier to public but that did not help.我尝试将其访问修饰符设置为 public 但这没有帮助。 I want to change the position of the character by whatever the X value becomes.我想通过 X 值变成什么来改变角色的位置。 So I was trying to essentially access that member of the form the class.所以我试图从本质上访问该类的表单成员。

I was attempting to do this inside the draw method, so it would update the input, then after that it would set the position, and then repeat the Draw method, looping constantly.我试图在 draw 方法中执行此操作,因此它会更新输入,然后设置位置,然后重复 Draw 方法,不断循环。

If there is a better way though, feel free to educate me.如果有更好的方法,请随时教育我。 How can I fix this?我怎样才能解决这个问题?

EDIT: Okay, I moved the methods into the UI, as mentioned by a comment.编辑:好的,正如评论中提到的那样,我将方法移到了 UI 中。 Here is what I have, but the sprite refuses to move:这是我所拥有的,但精灵拒绝移动:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Draw();
    }

    int X = 0;

    internal void Draw()
    {
        updateInput();

        pb_play.Location = new Point((pb_play.Location.X + X), 0);

        Draw();
    }

    internal void updateInput()
    {
        if (Keyboard.IsKeyDown(Key.Right))
            X = 5;
        else if (Keyboard.IsKeyDown(Key.Left))
            X = -5;
        else
            X = 0;
    }
}

I used a timer to fix the issue:我用一个计时器来解决这个问题:

internal void Draw()
    {
        pb_play.Location = new Point((pb_play.Location.X + X), (pb_play.Location.Y + Y));
    }

    internal void updateInput()
    {
        if (Keyboard.IsKeyDown(Key.Right))
            X = 1;
        else if (Keyboard.IsKeyDown(Key.Left))
            X = -1;
        else
            X = 0;

        if (Keyboard.IsKeyDown(Key.Up))
            Y = -1;
        else if (Keyboard.IsKeyDown(Key.Down))
            Y = 1;
        else
            Y = 0;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        updateInput();
        Draw();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM