unity debug ray is every time up to the object that is pointing

Viewed 26

Unity debug ray is every time up to the object that is pointing. Here one image of the problem.

public class PlayerCamera : MonoBehaviour{

[SerializeField] private Transform transformCamera, transformPlayer;
private Vector3 cameraPosition, playerPosition, cameraRotation;
[Range(0, 6.28f)] public float theta;
[Range(-1.57f, 1.57f)] public float phi;
public float standardCameraDistance = 5, provisionalCameraDistance;
private void Start()
{
    transformCamera.GetComponent<Transform>();
    transformPlayer.GetComponent<Transform>();

}
void FixedUpdate()
{
    playerPosition = transformPlayer.position;
    cameraPosition = transformCamera.position;
    MoveCamera();
}
void MoveCamera()
{
    cameraPosition.y += 1.0f;
    RaycastHit rayCastHit;
    Physics.Raycast(playerPosition, cameraPosition, out rayCastHit, standardCameraDistance);
    Debug.DrawRay(playerPosition, cameraPosition, Color.green);   }    }
1 Answers
  • Changing this local Vector3 field in cameraPosition.y += 1.0f; does in no way move the camera. You rather want to assign the result to transformCamera.position

    cameraPosition.y += 1.0f;
    transformCamera.position = cameraPosition;
    

    or directly without the need of a field

    transformCamera.position += Vector3.Up * 1.0f;
    
  • A ray consists of a start position and a direction. You are passing in a position (camera) as direction which is not what you want. You rather want the direction vector from playerPosition towards cameraPosition which is

     var direction = cameraPosition - playerPosition;
    
  • Are you really sure you want your camera moving up 1 Unit every 0.02 seconds? So 50 units per second?

so combined you would probably rather use something like

void MoveCamera()
{
    transformCamera.position += Vector3.Up * 1.0f * Time.deltaTime;

    var direction = cameraPosition - playerPosition;
    
    var isHit = Physics.Raycast(playerPosition, direction, out var rayCastHit, standardCameraDistance);
    
    Debug.DrawRay(playerPosition, direction.normalized * standardCameraDistance, isHit ? Color.green : Color.red);

    if(isHit)
    {
        // do something with rayCastHit
    }
}

Then also note that

transformCamera.GetComponent<Transform>();
transformPlayer.GetComponent<Transform>();

these are not doing anything at all! You either already have the references, then this is useless. Or it will throw exceptions since you can't use methods of something that isn't assigned.


And is there a special reason why you use FixedUpdate which is mainly used for Physics? You probably rather want to execute your code each frame in Update and multiply the movement by Time.deltaTime

Related