과제 설명
타임머신을 만들어 시간을 거슬러 올라가 게임 개발에 직접적으로 도움이 되는 놀라운 정리(피타고라스 정리)와 수학의 한 분야(삼각법)를 제공한 그리스인(특히 피타고라스와 히파르쿠스)을 만날 수 있다고 상상해 보세요! 다행히도 여러분은 컴퓨터 프로그래밍 실력을 뽐낼 수 있도록 컴퓨터(그리고 당연히 어떤 종류의 전원)를 가져가야 합니다.
이 과제에서는 두 점 사이의 거리와 게임 캐릭터가 두 번째 점에서 첫 번째 점으로 이동하기 위해 이동해야 하는 각도를 계산해야 합니다.
왜 중요한가요?
게임 개발에는 두 점 사이의 거리를 알아야 할 때가 많습니다. 예를 들어, NPC와 가장 가까운 지점을 기준으로 어떤 대상을 공격할지 결정할 수 있습니다. 각도는 어떨까요? 같은 예로, NPC가 선택한 목표물을 향해 어떻게 이동해야 하는지 알아내야 하는데, 각도를 알면 NPC에 적합한 속도 벡터를 만들 수 있습니다.
→ 두 좌표의 거리와 각도 구하기
Atan2 메서드
: 두 좌표로부터 각도(라디안)를 반환하는 메서드
탄젠트의 역함수인 아크탄젠트 θ=tan−1(xy)
제공코드의 메서드 분석
- split을 제공하지 않아서 직접 메서드 구현
/// <summary>
/// Extracts point coordinates from the given input string
/// </summary>
/// <param name="input">input string</param>
static void GetInputValuesFromString(string input)
{
// extract point 1 x
int spaceIndex = input.IndexOf(' '); // 첫 공백의 인덱스를 구함
point1X = float.Parse(input.Substring(0, spaceIndex)); //처음부터 공백 전까지의 문자열 point1X에 넣기
// move along string and extract point 1 y
input = input.Substring(spaceIndex + 1); // input의 범위를 공백 후의 문자열로
spaceIndex = input.IndexOf(' '); // 두번째 공백 인덱스
point1Y = float.Parse(input.Substring(0, spaceIndex));
// move along string and extract point 2 x
input = input.Substring(spaceIndex + 1);
spaceIndex = input.IndexOf(' ');
point2X = float.Parse(input.Substring(0, spaceIndex));
// point 2 y is the rest of the string
input = input.Substring(spaceIndex + 1);
point2Y = float.Parse(input);
#region Unfortunately, Mono doesn't have a Split method!
//string[] values = input.Split(' ');
//point1X = float.Parse(values[0]);
//point1Y = float.Parse(values[1]);
//point2X = float.Parse(values[2]);
//point2Y = float.Parse(values[3]);
#endregion
}
}
}
답안작성
using System;
namespace ProgrammingAssignment2
{
// IMPORTANT: Only add code in the section
// indicated below. The code I've provided
// makes your solution work with the
// automated grader on Coursera
/// <summary>
/// Programming Assignment 2
/// </summary>
class Program
{
// x and y coordinates for points
static float point1X;
static float point1Y;
static float point2X;
static float point2Y;
/// <summary>
/// Programming Assignment 2
/// </summary>
/// <param name="args">command-line args</param>
static void Main(string[] args)
{
// loop while there's more input
string input = Console.ReadLine();
while (input[0] != 'q')
{
// extract point coordinates from string
GetInputValuesFromString(input);
// Add your code between this comment
// and the comment below. You can of
// course add more space between the
// comments as needed
// 델타값과 피타고라스 빗변 구하기
float deltaX = (float)(point2X - point1X);
float deltaY = (float)(point2Y - point1Y);
float distant = (float)Math.Sqrt(deltaX * deltaX + deltaY * deltaY);
// 두 점 간의 각도 구하기
float radianAngle = (float)Math.Atan2(deltaY, deltaX); // Atan2는 두 점의 좌표로부터 각도(라디안)을 구함
float angle = radianAngle * (180 / (float)Math.PI);
// 거리와 각도 출력
Console.WriteLine(distant + " " + angle);
// Don't add or modify any code below
// this comment
input = Console.ReadLine();
}
}
/// <summary>
/// Extracts point coordinates from the given input string
/// </summary>
/// <param name="input">input string</param>
static void GetInputValuesFromString(string input)
{
// extract point 1 x
int spaceIndex = input.IndexOf(' ');
point1X = float.Parse(input.Substring(0, spaceIndex));
// move along string and extract point 1 y
input = input.Substring(spaceIndex + 1);
spaceIndex = input.IndexOf(' ');
point1Y = float.Parse(input.Substring(0, spaceIndex));
// move along string and extract point 2 x
input = input.Substring(spaceIndex + 1);
spaceIndex = input.IndexOf(' ');
point2X = float.Parse(input.Substring(0, spaceIndex));
// point 2 y is the rest of the string
input = input.Substring(spaceIndex + 1);
point2Y = float.Parse(input);
#region Unfortunately, Mono doesn't have a Split method!
//string[] values = input.Split(' ');
//point1X = float.Parse(values[0]);
//point1Y = float.Parse(values[1]);
//point2X = float.Parse(values[2]);
//point2Y = float.Parse(values[3]);
#endregion
}
}
}
피드백
float deltaX = point2X - point1X;
float deltaY = point2Y - point1Y;
// calculate distance and angle (in degrees)
float distance = (float)Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));
float angle = (float)Math.Atan2(deltaY, deltaX);
angle *= 180 / (float)Math.PI;
- float 타입캐스팅 안해도 되는데 잘못된 습관으로 불필요한 타입캐스팅을 함
- Math.Pow()라는 곱셈 메서드가 존재함
- angle 의 라디안에서 도로 변환하는 부분 참고