Calculate the reflection vector of the vector projected onto the object
Collision simulation:
public class test3 : MonoBehaviour
{
Vector3 dir;
Vector3 pos;
private void Start()
{
dir = transform.right;
pos = transform.position;
}
private void Update()
{
transform.position += dir * Time.deltaTime*4;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 inDirection = (transform.position - pos).normalized;
Vector2 inNormal = collision.contacts[0].normal;
dir = Vector2.Reflect(inDirection, inNormal);
pos = transform.position;
}
}
Ray Simulation:
Red line: inDirection
Green line: inNormal normal
Blue line: Result reflection line
public Transform tsTarget;//目标点
void OnDrawGizmos()
{
#if UNITY_EDITOR
Color prevColor = Gizmos.color;
//红线的方向
Vector3 dir = tsTarget.position - transform.position;
//从原点向终点打出一条红色的射线
Gizmos.color = Color.red;
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, dir, Mathf.Infinity);
Gizmos.DrawLine(transform.position, hitInfo.point);//画红线
//射线碰到碰撞物的法线
Gizmos.color = Color.green;
var normal = hitInfo.point + hitInfo.normal;//法线0,0点为基准,所以这里要加上碰撞点的位置
Gizmos.DrawLine(hitInfo.point, normal);//画绿线
Gizmos.color = Color.blue;
Vector2 direction = (Vector2)hitInfo.point + Vector2.Reflect((Vector2)dir, (normal - hitInfo.point));//Vector2.Reflect求反射,但是会出现偏移,经过我反复验证得出的结果
Gizmos.DrawLine(hitInfo.point, direction);//画蓝线
Gizmos.color = prevColor;
#endif
}