i want to make it so the enemy goes to attack mode only when he sees the player by raycasting at his position so if it will hit a wall the enemy will not attack only if the player can be “seen” by the enemy
so how do i script it ?
(java script)
thanks…
This is an extract from my AI script, its in C# but it should be pretty similar to what you would do on javascript
private Ray sight;
//.................................
void FixedUpdate(){
sight.origin = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
sight.direction = transform.forward;
RaycastHit rayHit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(sight, out rayHit, chaseRange)){
Debug.DrawLine(sight.origin, rayHit.point, Color.red);
if (rayHit.collider.tag == "Player"){
CurrentState = EnemyStates.following;
}
if (rayHit.collider.tag != "Player" && rayHit.collider.tag != "Enemy"){
CurrentState = EnemyStates.idle;
}
}
}
Study it thoroughly and apply your conclusions into your own script.
Also study the scripting reference
i tried it and unity said “A namespace can only contain types and namespace declarations”
Well that’s because that’s not the whole script, like I said its an extract, I give it to you so you can see how raycast works but I ain’t gonna code the script for you, you have to code it yourself or you wont learn anything.
i changed it to java it works thanks but if i want it to raycast to the player i mean whereever the player will be the enemy will try to raycast at him
You set direction to be player’s position minus enemie’s position.
Thats right. This is also from my script:
Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
target is the player object. damping its a float variable, the greater its value the faster the enemy with rotate towards the player