Swing/Reflection Vector

Reflection Vector Operation example

Soul-Learner 2016. 8. 15. 23:28

반사벡터를 구하기 위한 벡터 계산의 예


정반사 현상은 입사각과 반사각이 동일한 크기의 각을 이루고 벡터의 크기는 동일한 현상을 말한다. 


















  k : 입사각(벡터)  

  q : 반사각(벡터) 

  n : 반사판에 수직인 단위벡터

  -k:  입사벡터의 역벡터

  (-k ● n) : 역벡터와 수직벡터의 내적 값

  (-k ● n)n : 수직벡터의 완성



위의 그림을 해석하면 다음과 같다

1. 입사벡터의 역벡터를 구한다

2. 반사판에 수직인 단위벡터를 구한다

3. 역벡터와 수직 단위벡터간의 내적을 구한다

4. 수직단위벡터에 내적값을 곱해서 수직벡터를 완성한다

5. 입사벡터에 수직벡터를 두번 더해서 반사벡터를 구한다



위의 그림에 표시된 의미에 따라 벡터 연산을 통하여 반사벡터를 구하는 예


package org.kdea.swing.event;

public class Vector2D 
{
	double x,y;
	
	public Vector2D() {}
	
	public Vector2D(double x, double y){
		this.x = x;
		this.y = y;
	}
	
	public Vector2D add(Vector2D v){
		return new Vector2D(this.x+v.x, this.y+v.y);
	}
	
	public Vector2D sub(Vector2D v){
		return new Vector2D(this.x-v.x, this.y-v.y);
	}
	
	public Vector2D mul(double val){
		return new Vector2D(this.x*val, this.y*val);
	}
	
	public Vector2D div(double val){
		return new Vector2D(this.x/val, this.y/val);
	}
	
	public double length(){
		return Math.sqrt(x*x + y*y);
	}
	
	public double dot(Vector2D v){
		return this.x*v.x + this.y*v.y;
	}
	
	public Vector2D inv() {
		return new Vector2D(this.x*-1, this.y*-1);
	}
	
	/** 파라미터로 전달된 일반각(Deg)의 방향에 대한 수직벡터를 단위벡터로 리턴한다 */
	public static Vector2D getVertical(double deg){
		double rad = Math.toRadians(deg-90);
		double sinVal = Math.sin(rad);
		double cosVal = Math.cos(rad);
		return new Vector2D(cosVal, sinVal);
	}

	public static void main(String[] args) {
		/* 벡터(5,5)의 방향과 속도로 반사판에 충돌한 공이 정반사할 때의 반사벡터를 구해보세요
		*  반사판의 경사각도는 15도 이다
		*/
		Vector2D incVec = new Vector2D(5,5);
		System.out.printf("입사벡터의 성분: x(%f), y(%f) %n", incVec.x, incVec.y);
		Vector2D invVec = incVec.inv();
		System.out.printf("역벡터의 성분: x(%f), y(%f) %n", invVec.x, invVec.y);
		Vector2D vertVec = Vector2D.getVertical(15); //반사판에 수직인 단위벡터
		System.out.printf("반사판에 수직인 벡터의 성분: x(%f), y(%f) %n", vertVec.x, vertVec.y);
		double dotVal = invVec.dot(vertVec);
		System.out.printf("내적값: x(%f) %n", dotVal);
		vertVec = vertVec.mul(dotVal);
		System.out.printf("완성된 수직 벡터의 성분: x(%f), y(%f) %n", vertVec.x, vertVec.y);
		Vector2D reflVec = incVec.add(vertVec).add(vertVec);
		System.out.printf("반사 벡터의 성분: x(%f), y(%f) %n", reflVec.x, reflVec.y);
	}
}