2021-05-29

Elliptical G...


最近看视频做RPG,有个有趣的问题,比如控制角色的走动时候用Dup和Dright两个变量,范围都是[-1, 1],但是比如W键和D键同时按下时候算位移的Vector2时会有√2的问题,因为√(1+1)。
如果你考虑用clamp的话那么角色会很快加速过去了,这里有个论文讲Elliptical Grid Mapping,就是把一个正方形map到圆上,链接如下。

[论文URL]https://arxiv.org/ftp/arxiv/papers/1509/1509.06344.pdf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private Vector2 SquareToCircle(Vector2 input)
{
Vector2 output = Vector2.zero;
//公式如上图
output.x = input.x * Mathf.Sqrt(1 - (input.y * input.y) / 2.0f);
output.y = input.y * Mathf.Sqrt(1 - (input.x * input.x) / 2.0f);
return output;
}

···

void Update()
{
...
Vector2 tempDAxis = SquareToCircle(new Vector2(Dright, Dup)); //Dright和Dup是控制角色移动的,上面提到了

float Dright2 = tempDAxis.y;
float Dup2 = tempDAxis.x;
...

//下面就可以做其他的逻辑了
Dmag = Mathf.Sqrt((Dup2 * Dup2) + (Dright2 * Dright2));
Dvec = Dright2 * transform.right + Dup2 * transform.forward;
}