重装圆组件

时间:2019-06-28 10:40:28

标签: c# .net-core blazor

我正在尝试与Blazor制作一个圆形svg动画。我已经在俄罗斯方块游戏中看到了这一点,所以应该有可能我只是想不通如何使其工作。

<svg width="600" height="400">
    <Ball Height="@Ball.Height" Width="@Ball.Width" CurrentPosition="@Ball.CurrentPosition"></Ball>
</svg>

<button class="btn btn-primary" @onclick="@Bounce">bounce</button>

组件

@inherits BallModel;
@using Blong.Client.Model

<circle cx="@CurrentPosition.X" cy="@CurrentPosition.Y" r="@Radius" style="@Style" />

退回代码

 void Bounce()
    {
        for (int i = 0; i < 1000; i++)
        {
            Task.Run(() => SetPosition(Ball.CurrentPosition.X, Ball.CurrentPosition.Y++, GameHeight));
        }
    }

    public async Task<bool> SetPosition(int x, int y, int LastRow)
    {

        if (y <= LastRow)
        {
            Ball.CurrentPosition.Y++;
            Thread.Sleep(500);
            return true;
        }

        return false;

    }

这可以做些工作。每当我按下按钮时,我的球就会跳到新位置。有什么办法让它通过循环重新加载?我试图让我的球在屏幕上移动。

1 个答案:

答案 0 :(得分:1)

基本上,通知Blazor足以在循环内更新UI:

StateHasChanged();

但是很少。首先,SetPosition方法不包含任何等待,将同步运行。

如果您不想阻止主线程,则可以使Bounce异步,而不是自己创建新任务。

此外,GameHeight在当前View的状态下似乎是常量或静态的,因此我将直接在调用的方法中引用它,而不是将其作为参数传递,但这只是个人观点。

另一件事是,确保在“弹跳”时不会多次调用“弹跳”。

我认为逻辑线圈要简化一些。

这是我的建议:

public async Task Bounce()
{
  if(Bouncing) return;

  Bouncing = true;

  while(Ball.CurrentPosition.Y <= GameHeight)
  {
    Ball.CurrentPosition.Y++;
    StateHasChanged();
    await Task.Delay(500);
  }
// in case View has been resized, make sure Ball is not out of boundaries
  Ball.CurrentPosition.Y = GameHeight;
  StateHasChanged();
  Bouncing = false;
}