0

嘿,我是 C# 图形编程的新手。我需要知道如何在我的窗口窗体中沿角度方向移动椭圆。我已经使用我的代码成功地将我的椭圆移动到默认方向。


我的代码:

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;  
    }


}
  }

简而言之,我的椭圆只是沿对角线移动!所以简单来说问题是我是否可以像 30' 或 80' 或指定角度那样移动它!


在此处输入图像描述

4

2 回答 2

2

我相信您正在寻找一些基本的三角函数,例如:

x = cos(degrees) * maxX;
y = sin(degrees) * maxY;
于 2014-04-02T14:45:28.610 回答
1

Rectangle.X / Y 是int,添加到这样的整数至少会为 X 或 Y 添加 +1,这会导致对角线移动。

dx 和 dy 应该是floator double。对于 X 和 Y 坐标,您也必须有一个浮点变量并用它进行计算。计算后,您可以将自己的 X / Y 分配给矩形。

从您的代码中,您应该更多地编写:

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;

然后像这样在你的计时器中计算:

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

可以在计时器中通过根据您到达的一侧否定 dx 或 dy 来完成对墙壁的反射。

如果你想使用角度作为输入来计算 dx 和 dy 你可以这样做:

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

速度是每个计时器调用的像素移动。

于 2014-04-02T14:42:41.863 回答