Domanda

hey there I am new to C# Graphics Programming. I need to know how can I move an Ellipse inside my windows form in angular directions. I have been successfully moved my Ellipse in default direction using my code.


My Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Paddle_Test
{
    public partial class Form1 : Form
    {
        Rectangle rec;
        int wLoc=0;
        int hLoc=0;
        int dx=3;
        int dy=3;

    public Form1()
    {
     InitializeComponent();
     rec = new Rectangle(wLoc,hLoc , 100, 10);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Refresh();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.FillEllipse(new SolidBrush(Color.Blue), rec);

    }

    private void timer_Tick(object sender, EventArgs e)
    {
        //moving inside my timer
        rec.X += dx;  
        rec.Y += dy;  
    }


}
  }

In simple words my Ellipse is only moving diagonally! So the Question in simple words is is it possible for me to move it like 30' or 80' or Angle Specified!


enter image description here

È stato utile?

Soluzione

I believe you're looking for some basic trigonometry functions, like:

x = cos(degrees) * maxX;
y = sin(degrees) * maxY;

Altri suggerimenti

Rectangle.X / Y is int, adding to an integer like this will at least add +1 to X or Y which causes the diagonal movement.

dx and dy should be float or double. For the X and Y coord you must have a floating point variable too and calculate with it. After calculation you can assign your own X / Y to the rectangle.

From your code you should more write:

public partial class Form1 : Form
{
    Rectangle rec;
    int wLoc=0;
    int hLoc=0;
    double xpos=0;
    double ypos=0;
    double dx=0.3;
    double dy=0.6;

and then calculate in your timer like this:

xpos += dx;
ypos += dy;
rec.X = xpos;
rec.Y = ypos;

Reflecting on walls can be done in the timer by negating dx or dy depending on the side you reached.

If you want to use angle as input to calculate dx and dy you can do it this way:

xpos += cos(angleInDegrees / 360.0 * 2 * Math.PI) * speed;
ypos += -sin(angleInDegrees / 360.0 * 2 * Math.PI) * speed;
rec.X = xpos;
rec.Y = ypos;

Speed is movement in pixels per timercall.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top