I’m trying to program a Pokemon-like movement(Fire Red) and I was doing ok until I had to use Raycasting. The thing is I’m using a single script to handle the movement of two GameObjects because the thing is that you can control two characters and I want the movent to occur only if the two characters can move. So I put a bool function to check the path and that’s where things started getting messy.
A Raycast needs a Direction, but I’m using a Vector2, so I tried using Transform.TransformDirection(); but it’s not working because the Raycast is aways going to the Left, varying only in distance. What am I doing wrong?
(PS.: If you’re having problems understanding the code and need to test it just delete the “THIS IF” check and try it on Unity.
Basicaly I’m using 3 functions, one to receive the Input, another to calculate the position that each GameObject should go to and the last one to actually execute the movement of each GO.)
void Movement()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
//Swap movement direction check
if (Input.GetKeyDown(KeyCode.X))
{
movementDirection *= -1;
}
//If player gives any Input
if (h != 0)
{
/* Test this to see both Raycasts at the same time. They are aways going to the same direction
CheckPosition(h, 0, boy);
CheckPosition(h * movementDirection, 0, shadow);
*/
//Call the movement function if there's nothing on the place
if (CheckPosition(h, 0, boy) && CheckPosition(h*movementDirection, 0, shadow)) //THIS IF
{
isMoving = true;
CalculateNewPosition(h , 0, boy);
CalculateNewPosition(h * movementDirection, 0, shadow);
}
}
}
bool CheckPosition(float h, float v, GameObject player)
{
Vector2 newPos = new Vector2(player.transform.position.x + h, player.transform.position.y + v);
//Testing the Raycast You can see the problem here
Debug.DrawRay(player.transform.position, player.transform.TransformDirection(newPos), Color.yellow, 1f);
/* I MIGHT'VE MESSED THIS UP A LITTLE BUT THE PROBLEM IS UP HERE /\
if (!Physics2D.Raycast(player.transform.position, player.transform.TransformDirection(newPos), 2f))
{
return true;
}
else
{
return false;
}
*/
}
void CalculateNewPosition(float h, float v, GameObject player)
{
Vector2 newPos = new Vector2(player.transform.position.x + h, player.transform.position.y + v);
StartCoroutine(Go(player, newPos));
}
// Function that actually makes the characters move around
IEnumerator Go (GameObject player, Vector3 newPos)
{
float newTime = 0;
while (true)
{
newTime += Time.deltaTime;
player.transform.position = Vector2.Lerp(player.transform.position, newPos, newTime);
if (player.transform.position != newPos)
{
yield return null;
}
else
{
player.transform.position = newPos; //Doing this because Lerping is missing the actual position by a really small fraction like 0.0000001
isMoving = false;
yield break;
}
}
}