In my tile-based game I want to visualize the Field of View for my enemies. They can only look in two directions (forwards and backwards) so I don’t want a cone-shaped Field of View but rather a rectengular. For this I have created a Cube Gameobject and made it a child to an enemy.
With a Raycast I find out wether the enemy can see my player or if his vision is blocked by an Obstacle.
Now for the Sightline Object I only want the Cube to scale up to the Raycast.hitpoint of where the next Obstacle is. Here is my Code for this (I left some parts out that aren’t important to this problem) :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChickenSightVer : MonoBehaviour
{
public GameObject player;
public GameObject sightline;
float rayLength = 20f;
RaycastHit hitpoint1;
void Update()
{
Raycast();
}void DrawSightline(RaycastHit hitpoint)
{
sightline.transform.localScale = new Vector3(0.5f, hitpoint.point.z, 0.5f);
}
void Raycast()
{
Ray myRay3 = new Ray(transform.position + new Vector3(0, 0.15f, 0), -transform.forward);
Debug.DrawRay(myRay3.origin, myRay3.direction, Color.red);
if (Physics.Raycast(myRay3, out hitpoint1, rayLength))
{
if (hitpoint1.collider.tag == "Obstacle")
{
DrawSightline(hitpoint1);
}
}
}
}
The Sightline Object scales at runtime but not how I intended it. Sometimes the “hitpoint.point.z” has negative values and I can’t seem to figure out why.
Grateful for any suggestions or solutions! Thank you!
I don’t know why sometimes you get negative values, but I do know that when you convert hotpoint.point.z to an absolute value it will always be a positive number, like so : Mathf.Abs(hitpoint.point.z)
I hope this can visualize my problem a little better. The obstacles are white and the sightline object is pink-ish red.
My problem isn’t that it takes negative values it just seemed odd to me. As you can see the sightline object scales to some “random” point.
The problem is twofold. First you are trying to set localScale based on the value of hitpoint.point.z, but that is just the world position of the hitpoint, instead use the distance between the origin of the sightLine object and the hitpoint and set that as the localScale. Second, make sure the sightLine object’s origin y is set, not to the middle of the object, but at y 0.
To modify the origin of an object you’ll need to use some 3d modelling software like Blender.
Edit: You can see for yourself that hitpoint.point.z is exactly where you think it is by temporarily commenting out the code that sets the localscale of the object, and add a line of code that sets the position of the sightLine object to be hitPoint.point’s position. The distance you see between the enemy and the sightLine object (now at the location of the hitPoint.point position) is what you need to set the localScale of the sightLine.