Search code examples
c#picturebox

C# make a picturebox run away from another picturebox


Okey, so I'm working on a "mini-game": you are a cat and you need to catch a mouse. I'm trying to make a mouse (picturebox) run away from a cat (picturebox) IF the cat is closer than 10 pixels (or 15 or whatever) to the mouse, then mouse starts running to another direction. If it the cat is not that close, then the mouse stays where it is. I have option that wherever the cat is, the mouse is running away to the opposite direction, but I want it to move ONLY IF the cat is closer than 10 px and I can't do that, I don't know how. I've tried some options, but didn't work. Could you help me? Or give some tips? Thank you.


Solution

  • You can calculate distance between two positions easily using Pythagorean theorem. Taking when mouse has coordinates [x1,y1] and cat [x2,y2], you can then easily check

    if ( ( ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) ) <= ( 10 * 10 ) )
    {
       //closer than 10px
    }
    

    Here I am taking 10px even diagonally. The comparison is to 100, because doing square root is a computationally expensive operation so it is much easier to compare the squared sides of the inequality.