- Home /
What is the Best way to use Raycast for enemy Fire?
I want to use ray cast to damage my player with a for loop. How would I do this? I am not to familiar with for loops. Please show me how to correctly use a for loop.. thank you!
Ahhh! I didn't use your code, but you gave me an idea. I got it working thanks!
Please edit your answer to show your solution, so others can see exactly how you resolved this.
Answer by noooodley · Aug 12, 2013 at 07:44 AM
Is the for loop mandatory? You can easily do what you are describing without a for loop.
As for how for loops work, I would recommend reading the following page, as there is no use in me rewriting what has already been written:
The for loop is not mandatory. Just looking for the best solution shoot a raycast at the player in 2 second time increments. Any ideas?
I know i can use InvokeRepeating but is there another way to do this loop cycle? maybe in a corontine? or another way?
Something like this would probably work:
public float timeBetweenShots = 2f;
private float lastShotTime = 0;
private void Update() {
//check to see if it is time to shoot
if (Time.time - lastShotTime > timeBetweenShots) {
//setup the ray however you need, this is just an example
Ray myRay = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit myRayHit;
//do the raycast
if (Physics.Raycast(myRay, out myRayHit) {
//put code here to damage the player
}
//set 'lastShotTime' to the current time
lastShotTime = Time.time;
}
}
Hope this helps. Does this answer your question?
Answer by Triqy · Aug 12, 2013 at 08:25 PM
Im not at home right now but here is a rough answer that i came up with...
var shotTimer: float;
var DamagePerSecond = 1;
var OpenFire = false;
function Update()
{
shotTimer = Time.deltaTime * DamagePerSecond;
if(shotTimer > 1)
{
OpenFire = true;
shotTimer = 0;
}
else
OpenFire = false;
if(OpenFire == true)
{
//Shoot Raycast at Player
// if(Raycvast hits player collider)
// {
// player.playerHealth -= 1;
// }
}
}
This is rough and not exactly how i did it pertaining to my project because i used triggers to register to see if enemy is within a certain distance. But here is a revised answer!
This doesn't appear to be a feasible solution. Please don't accept something that is not a working resolution. If you still need help, keep the answer open. If you don't wish to post an actual working solution, but have resolved the problem, please simply close the question.
Your answer
![](https://koobas.hobune.stream/wayback/20220613112026im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Enemy damage error 1 Answer
Making bullet holes in enemies. 1 Answer
Enemy to move out of way of player 1 Answer
ApplyDamage Error 0 Answers
Fall Damage Script Problem? 1 Answer