在窗口边缘弹跳球向相反方向移动

时间:2017-11-25 17:35:37

标签: c# wpf visual-studio visual-studio-2017 intersection

我尝试制作一个弹跳矩形,然后设法检测窗口/画布的边缘/边框。我试着让计时器停在边缘并且工作正常。我手动定义了边缘。我的问题是,一旦撞到边界,矩形就会朝相反方向移动。在我的代码中,当它到达边界时,它只是快速前后移动而不是实际改变位置。它有点震动。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    DispatcherTimer t;
    int ballvX1, ballvY1, ballvX2, ballvY2;
    public void movement(Rectangle r, int ballvX, int ballvY)
    {
        var BallX = Canvas.GetLeft(r);  //position left
        var BallY = Canvas.GetTop(r);  //position up 
        if((BallX <= 1)||(BallX >= 455))
        {             
            ballvX = -ballvX;
        }
        if((BallY <= 10)||(BallY >= 270))
        {
            ballvY = -ballvY;
        }
         Canvas.SetLeft(r, BallX + ballvX);
         Canvas.SetTop(r, BallY + ballvY);
    }
    public MainWindow()
    {
        InitializeComponent();
        t = new DispatcherTimer();
        t.Interval = new TimeSpan(177777);
        t.Tick += T_Tick; ;
    }
    private void T_Tick(object sender, EventArgs e)
    {
        movement(r1, ballvX1, ballvY1);
        movement(r2, ballvX2, ballvY2);
        var BallX1 = Canvas.GetLeft(r1);  //position left
        var BallY1 = Canvas.GetTop(r1);  //position up 
        Rect r1new = new Rect(BallX1, BallY1, r1.ActualWidth, 
        r1.ActualHeight);
        var BallX2 = Canvas.GetLeft(r2);  //position left
        var BallY2 = Canvas.GetTop(r2);  //position up 
        Rect r2new = new Rect(BallX2, BallY2, r2.ActualWidth, 
        r2.ActualHeight);
        if (r1new.IntersectsWith(r2new))
        {
            t.Stop();
        }

    }

    private void b1_Click(object sender, RoutedEventArgs e)
    {
        Random rnd = new Random();
        ballvX1 = rnd.Next(-11, 10);
        ballvY1 = rnd.Next(-11, 10);
        ballvX2 = rnd.Next(-11, 10);
        ballvY2 = rnd.Next(-11, 10);
        t.Start();
    }

    private void b2_Click(object sender, RoutedEventArgs e)
    {
        t.Stop();
    }

    private void b3_Click(object sender, RoutedEventArgs e)
    {
        t.Stop();
        Canvas.SetLeft(r1, 172);
        Canvas.SetTop(r1, 146);
        Canvas.SetLeft(r2, 423);
        Canvas.SetTop(r2, 56);
    }
}
}

如果有人知道如何解决这个问题,我将非常感激。 BTW有两个矩形,但我给它们两个相同的运动功能,一旦它们遇到它们就停止了,但我认为它与问题无关。

0 个答案:

没有答案