Hi there,
I’m following a beginners tutorial about raycasts at the moment which consists of a turret that the player is able to rotate left and right on the z-axis and fire a raycast from the top of the turret towards three possible targets. When the raycast has hit one of the targets it outputs a message in the console stating which target was hit.
Here is a video of what the end result of the tutorial looks like:
And here is the code shown below here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
private float _moveInput;
public LayerMask target;
// Update is called once per frame
void Update()
{
_moveInput = Input.GetAxis("Horizontal");
transform.Rotate(0, 0, -_moveInput);
if (Input.GetKeyDown(KeyCode.Space))
{
RaycastHit2D hit = Physics2D.Raycast(transform.position,transform.TransformDirection(Vector2.up),10f,target);
Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * 10f, Color.red);
if (hit)
{
Debug.Log(hit.collider.name + " has been hit with a raycast!");
}
}
}
}
As you can see in the above code the tutor uses a thing called “Transform.TransformDirection” which I don’t understand fully. My basic understanding of this function is that it takes the co-ordinate values that is stored within a vector and translates them to world space?
If I was to replace the second parameter in the Physics2D.Raycast method in the if statement with just “Vector2.up” the raycast just fires straight up regardless of the z-value of the “local rotation” of the player game object. I don’t understand why this is? It seems that the Transform.TransformDirection function makes sure the origin of the raycast will start at the top of the turret in the direction that it is pointing towards.
I’ve been looking at videos on Youtube about the difference between local and world space but it still doesn’t help me understand the above example I have described.
Any helpful information about my question would be appreciated