- Home /
Raycast always hitting the same place even if I click different areas?
void Update() { RaycastHit hit; if (cm.glareOn == true) { if (Input.GetMouseButtonDown(0)) {
GameObject bullet = Instantiate(lightbullet, Input.mousePosition, Quaternion.identity);
if (Physics.Raycast(origin.transform.position, origin.transform.forward, out hit))
{
Debug.Log(hit.transform.position);
bullet.transform.position = Vector3.MoveTowards(origin.transform.position, hit.transform.position, speedbullet * Time.deltaTime);
}
}
}
}
Answer by Hellium · Oct 25, 2021 at 09:15 AM
hit.transform
is returns the Transform of the object hit by thee raycast, not the raycast impact point
bullet.transform.position = Vector3.MoveTowards(origin.transform.position, hit.point, speedbullet * Time.deltaTime);
Several other notes about your code:
Instantiate(lightbullet, Input.mousePosition, Quaternion.identity);
.Input.mousePosition
is a screen-space position, not a world space position. You most likely want to spawn the bullet at the barrel's position (maybeorigin.transform.position
?)
Moving the bullet once under
Physics.Raycast
does not really make sense. You most likely want your bullet to travel on its own over time. You'll find several examples on the web to help you with that.
@Hellium thank you but the hitpoint doesnt change either
Then, please explain the actual issue you are facing. Images may help.
Have you solved the two other issues I've mentioned?
So basically I managed to get it to shoot now, thank you for your suggestion :) but it still only shoots in one direction no matter where I click. it only shoots in that direction and I can't get it to change. Also I made a new script for the bullet void Update() { transform.position = Vector3.MoveTowards(transform.position, am.target, 30 * Time.deltaTime); }
so it is shooting properly now but still only to one point and not the point i am clicking
I am sorry if it is unclear and thank you for all your help!
Answer by AwptiK · Oct 25, 2021 at 11:34 AM
Perhaps do it something like:
bullet.transform.position += new Vector3(0, 0, speed);
Or:
bullet.transform.position = Vecto3.Lerp(transform.position, hit.point, speed);
where speed is how fast the bullet moves. Put these in FixedUpdate(). If you want them in Update() multiply speed by Time.DeltaTime.
thank you, but i think my problem is that the raycaster only hits one area. the object in front of the camera has a box collider but it still can't seem to hit it(it hits the back plane) and the hit point doesn't change no matter what ,:)