user1221876
user1221876

Reputation: 61

Move the random object when mouse reaches the position of the point

I am trying to generate random points on the canvas. So i want to the random point on the screen to move to a new random location, when mouse touches it. How do i do this?? this is not happening with any of the mouse events. An example would be appreciated.

Upvotes: 1

Views: 1365

Answers (1)

user1246682
user1246682

Reputation: 206

Well you can attach MouseMove event with rectangle and handle the random positioning of rectangle in this event.

Updated Referring to the answer in this link - Move a rectangle around a canvas. You need to update Add Click event in this way -

    private void Add_Click(object sender, RoutedEventArgs e)
    {
        Point newPoint;
        Rectangle rectangle;

        newPoint = GetRandomPoint();
        rectangle = new Rectangle {Width = 4, Height = 4, Fill = Brushes.Red};
        rectangle.MouseMove += new MouseEventHandler(rectangle_MouseMove);
        m_Points.Add(newPoint);
        PointCanvas.Children.Add(rectangle);
        Canvas.SetTop(rectangle,newPoint.Y);
        Canvas.SetLeft(rectangle,newPoint.X);
    }

    void rectangle_MouseMove(object sender, MouseEventArgs e)
    {
        Rectangle rectangle = sender as Rectangle;
        Point newPoint;
        newPoint = GetRandomPoint();
        Canvas.SetTop(rectangle, newPoint.Y);
        Canvas.SetLeft(rectangle, newPoint.X);
    }

I have attached the MouseMove event with rectangle when we create it and then moving the rectangle randomly in this event. Hope this helps you!!

Upvotes: 1

Related Questions