I just started working with Unity aaaaand right away I need your help ^^".
In theory it should return a boolean if a Target can be hit and that it does. However I do believe, since I dont have much expirience with Raycasts that the ray does not follow the rotation fot he object, this script is attached to, wich is what I want.
To put it even more simple:
If the object “faces” the target, “true” shall be returned.
var hit : RaycastHit;
var direction = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast (transform.position, direction, hit, attackRange))
return true;
else
return false;
}
Thanks in advance and sorry for my bad english ^^"
I think that you don’t call CanHitTarget() at the time when it’s needed. I wrote you an example of what you could do to make things easier:
static var targetInSight : boolean = false;
var target : Transform;
private var attackRange : int = 100;
private var lastObject : GameObject;
function Update () {
var hit : RaycastHit;
var direction = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast (transform.position, direction, hit, attackRange)) {
if(hit.collider.gameObject!=lastObject){
if(hit.collider.gameObject.transform==target){
targetInSight=true;
print("I'm looking at "+hit.collider.name+" which is my target.");
} else {
targetInSight=false;
print("I'm looking at "+hit.collider.name+" and I have no clue what this is.");
}
}
lastObject=hit.collider.gameObject;
}
}
The thing is that here it casts a ray on every update, which could get a bit heavy (depending on your other game logic). So you could also put this into a function which only calls if certain actions is being made by your GameObject (such as when it’s in a specific area/distance to the player and if it’s moving/rotating).
Here’s an example of this in a function which only updates on the “watcher’s” movement and rotation:
var target : Transform;
private var attackRange : int = 100;
private var lastObject : GameObject;
private var lastRotation = Quaternion.identity;
private var lastPosition : Vector3;
function Update () {
if(transform.position!=lastPosition||transform.rotation!=lastRotation){
if(checkForTarget()) {
print("I'm looking at my target.");
} else {
print("I'm lost lonely and confused.");
}
lastPosition=transform.position;
lastRotation=transform.rotation;
}
}
function checkForTarget() : boolean {
var hit : RaycastHit;
var direction = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast (transform.position, direction, hit, attackRange)) {
if(hit.collider.gameObject.transform==target) {
return true;
} else {
return false;
}
}
}
This is just an example as you probably would want to check for player movement and distances also. The first example is easier to implement, the second should later be used for optimizations taken your specific variables into consideration.