计算从广场中心的载体,边缘基于RADIUS [英] Calculate a vector from the center of a square to edge based on radius

查看:175
本文介绍了计算从广场中心的载体,边缘基于RADIUS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个正方形(由X,Y,宽度,高度描述)和角度(弧度)我需要计算该起源于正方形中心并终止于与该正方形的在边缘碰撞的点的矢量给定的角度。

Given a square (described by x, y, width, height) and an angle (in radians) I need to calculate a vector that originates at the squares centre and terminates at the point that collides with the edge of the square at the given angle.

我真的最感兴趣,在这样的碰撞点,如果这将使计算更有效的让我知道。

I'm really most interested in the point it collides at so if that would make calculation more efficient let me know.

这个问题能推广到矩形?怎么样在一般的多边形?

Can this be generalized to Rectangles? How about polygons in general?

推荐答案

的载体将是中心+(COS(角度),罪(角度))*幅度。既然要与一个正方形相交这一点,你需要确定震级。你可以得到与方:

The vector will be center + (cos(angle), sin(angle))*magnitude. Given that you want to intersect this with a square, you need to determine magnitude. You can get that with a square with:

float abs_cos_angle= fabs(cos(angle));
float abs_sin_angle= fabs(sin(angle));
if (width/2/abs_cos_angle <= height/2/abs_sin_angle)
{
    magnitude= fabs(width/2/abs_cos_angle);
}
else
{
    magnitude= height/2/abs_sin_angle;
}

不过,COS(角度)或罪(角度)可能为零,所以你应该跨乘了这一点得到:

However, cos(angle) or sin(angle) could be zero, so you should cross multiply that out to get:

float abs_cos_angle= fabs(cos(angle));
float abs_sin_angle= fabs(sin(angle));
if (width/2*abs_sin_angle <= height/2*abs_cos_angle)
{
    magnitude= width/2/abs_cos_angle;
}
else
{
    magnitude= height/2/abs_sin_angle;
}

你可以平凡拿到终点从。

And you can trivially get the end point from that.

编辑:这里有一个片段,你可以在地方下降,以验证该工作原理与目前公认的答案:

Here's a snippet you can drop in place to verify this works with the currently accepted answer:

	double magnitude;
	double abs_cos_angle= fabs(cos(angle));
	double abs_sin_angle= fabs(sin(angle));
	if (width/2*abs_sin_angle <= height/2*abs_cos_angle)
	{
		magnitude= width/2/abs_cos_angle;
	}
	else
	{
		magnitude= height/2/abs_sin_angle;
	}

	double check_x= x + cos(angle)*magnitude;
	double check_y= y + sin(angle)*magnitude;

	printf("  a = %d deg: x = %lf; y = %lf\n",(int)(angle/pi*180),check_x,check_y);

显然,这是适用于轴排列的长方形。你可以通过寻找测试向量和多边形的每条边的最接近的交点类似的东西。 (您可以进一步优化的,但是这将作为练习留给读者。)

Clearly this is applies to an axis aligned rectangle. You can do something similar by finding the closest intersection between the testing vector and every edge in a polygon. (You can optimize that further, but that's left as an exercise to the reader.)

这篇关于计算从广场中心的载体,边缘基于RADIUS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆