- Home /
What am I doing wrong
I just tried to convert the following script, http://wiki.unity3d.com/index.php/ShootingWeaponScript
from C# to Java script and I got everything working except for one part and I am not sure what I am doing wrong. Here is the code that I am working with.
var projecile : Rigidbody;
var speed = 20;
var projMuzzleVelocity : float = 6.0; // in metres per second
var RateOfFire : float = 6.0;
var Inaccuracy : float = 6.0;
var fireTimer : float = 6.0;
function Start()
{
fireTimer = Time.time + RateOfFire;
}
function Update ()
{
if( Input.GetButtonUp("Fire1"))
{
Debug.DrawLine(transform.position, transform.position + transform.forward, Color.red);
if (Time.time> fireTimer)
{
//GameObject.projectile;
var muzzleVelocity : Vector3 = transform.forward;
if (Inaccuracy != 0)
{
var rand : Vector2 = Random.insideUnitCircle;
muzzleVelocity += new Vector3(rand.x, rand.y, 0) * Inaccuracy;
}
muzzleVelocity = muzzleVelocity.normalized * projMuzzleVelocity;
//Debug.Log("Fire1");
clone = Instantiate(projecile, transform.position, transform.rotation);
//clone.velocity = transform.TransformDirection(muzzleVelocity);
clone.velocity = transform.TransformDirection(Vector3(0,0,speed));
fireTimer = Time.time + RateOfFire;
Destroy(clone.gameObject,1.5);
}
}
}
So I have tracked the problem to the following line but I am not sure how to make this work.
clone.velocity = transform.TransformDirection(Vector3(0,0,speed));
If I make the above like this
clone.velocity = transform.TransformDirection(muzzleVelocity);
everything will work but the player will only shot in one direction. So for example they will always shoot forward, even if they are standing backwards. Like I stated before I am pretty sure that it has something to do with how I am using muzzleVelocity but I am not sure that I am doing wrong.
Answer by Dave-Carlile · May 15, 2013 at 07:48 PM
You should be able to use transform.forward to get the direction the object is facing.
clone.velocity = transform.forward * muzzleSpeed;
The forward
property is a unit length vector, so you can just multiply that by the speed in order to create the desired velocity vector.
Thanks for the response, I did end up getting it working. by adding the following line of code.
clone.velocity = muzzleVelocity;
so now everything is working the way that I wanted it to. Thanks for the help.
@Samsterdamn - if your question is answered, please click on the checkmark next to the answer to close it out.
Your answer
Follow this Question
Related Questions
Picking up and Dropping Weapons 1 Answer
How to add rigidbody with script? 1 Answer
Problems instantiating a prefab (javascript) 1 Answer
[Q] 3d engine for MIPS android platform 0 Answers
How to block a raycast? (Java) 1 Answer