[英]C# 2D Vector Movement - speed and direction
我正在做一个(可能是简单的)任务,我想让一个绘制的对象移动到用户控制(也绘制)。 我所拥有的是球员X和Ycoördinate,分别定义为Xp和Yp。 必须移动(触发后,不包含在此处的代码中)到'player-object'的对象在this.X和this.Y中定义了它的coördinates。
int xDirection = Xp - this.X;
int yDirection = Yp - this.Y;
int angleInDegrees = (int)Math.Atan2(xDirection, yDirection);
double radians = (Math.PI / 180) * angleInDegrees;
double xTmp = 3 * Math.Cos(radians);
int xSpeed = (int)xTmp;
double yTmp = 3 * Math.Sin(radians);
int ySpeed = (int)yTmp;
Console.WriteLine(xDirection);
Console.WriteLine(yDirection);
Console.WriteLine(xSpeed);
Console.WriteLine(ySpeed);
Console.ReadLine();
这并没有给我正确的数字,所以我想知道可能是什么错。
关于这一点最棘手的事实可能是必须移动到玩家对象的物体可以从所有侧面(360度)接近但是没有可用的接近角度。
蒂姆,我希望能完成我的问题
Math.Atan2以弧度为单位返回一个值,其他c#三角函数也是如此。
double angle = Math.Atan2(yDirection, xDirection);
还要确保强制类型转换为小数:
3.0 * Math.Cos(radians);
我打赌你看到的主要问题是这一行:
int angleInDegrees = (int)Math.Atan2(xDirection, yDirection);
正如@catflier所提到的, Math.Atan2
以弧度为单位返回角度(因此数字范围为0到2pi)。 但是,您执行转换为int
将截断小数位。 因此,如果您的角度为45度,那实际上会返回~0.785398弧度。 强制转换为int
会将其变为0
。 类似地,在90度,即~1.570796弧度,对int
强制转换将导致1
。 这是一个重大的舍入错误。 正如我在评论中提到的,考虑将所有类型更改为双精度,并且只在最后一点执行整数强制转换(我假设您的对象基于整数定位)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.