- Home /
Bullet Spread with Raycast/RigidBody Triangulation?
I know this is a probably incredibly noob-ish question, but is it possible to have bulletspread with a rigidbody that is controlled using Raycast triangulation? Here is an example of the script I am using:
#pragma strict
var spawnPoint: Transform;
var projectileSpeed: float = 20;
var projectilePrefab: Transform;
function Update () {
if (Input.GetButtonDown("Fire1")){
var ray: Ray = Camera.main.ViewportPointToRay(Vector3(0.5,0.5,0));
var hit: RaycastHit;
var dir: Vector3;
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.yellow);
if (Physics.Raycast(ray, hit)){
dir = (hit.point - spawnPoint.position).normalized;
}
else {
dir = ray.direction;
}
var rot = Quaternion.FromToRotation(projectilePrefab.forward, dir);
var projectile = Instantiate(projectilePrefab, spawnPoint.position, rot);
projectile.rigidbody.velocity = dir * projectileSpeed;
}
}
If there isn't a way, then is it possible to triangulate two raycasts instead of a raycast and a rigidbody?
Thanks so much in advance. :P
I've read your question a couple of times, and don't understand what you are asking. Note your line 20 seems wrong to me for triangulation. I would expect something like:
dir = (ray.GetPoint(someDefaultDistance) - spawnPoint.position).normalized;
Aha, I apologize for the wording of it. I was wondering whether or not the projectile could choose a random space within a y/x plane(In relation to the player) from where the ray and rigidbody are supposed to intercept, so as to simulate bullet spread at the intercept. And thank you for the correction, I partially see where I had gone wrong.
Answer by robertbu · Aug 30, 2014 at 03:27 AM
Assuming you don't allow the user to shoot straight up or down, you can do this:
var v3Offset = Vector3.Cross(Vector3.up, dir) * Random.Range(0.0, variance);
v3Offset = Quaternion.AngleAxis(Random.Range(0.0, 360.0), dir) * v3Offset;
dir += v3Offset;
This code goes between line 21 and 22. 'variance' is either a variable you define or is replaced by a constant. It represents the maximum variation you will allow in dir at 1 unit. Obviously the amount of variance at the hit point will be greater (assuming the hit point is more than one unit away) just as would be with a real gun. The code works by first finding a vector orthogonal to 'dir', then sizing that vector between 0.0 and variance, randomly rotating that vector using 'dir' as an axis, finally adding the result to 'dir' to create the imprecision.
Your answer
Follow this Question
Related Questions
Realistic Bow and Arrow Physics? 2 Answers
Best way to shoot physical bullets? 2 Answers
2.5D Shooting Rigidbodies vs RayCasts 0 Answers
Bullet collision for space shooter - colliders, rays, etc? 2 Answers