2D sidescroller Projectile Script

Hello, I’m making a simple 2D sidescroller game. In the game, I want the player to be able to throw a projectile. I used a script from the Script Reference that comes with unity and modified it a little bit.

	// Instantiate a rigidbody then set the velocity

	var projectile : Rigidbody;

	function Update () {
		// x was pressed, launch a projectile
		if (Input.GetKeyDown("x")) {
			// Instantiate the projectile at the position and rotation of this transform
			var clone : Rigidbody;
			clone = Instantiate(projectile, transform.position, transform.rotation);
			
			// Give the cloned object an initial velocity along the current 
			// object's z axis
			clone.velocity = transform.TransformDirection (Vector3.forward * 10);
		}
	}

When I play the game and use a projectile, it creates 2 errors.

“Actor::updateMassFromShapes: Compute mesh inertia tensor failed for one of the actor’s mesh shapes! Please change mesh geometry or supply a tensor manually!
UnityEngine.Object:Instantiate(Object, Vector3, Quaternion)
projectile:Update() (at Assets/script/projectile.js:10)”

&

“InvalidCastException: Cannot cast from source type to destination type.
projectile.Update () (at Assets/script/projectile.js:10)”

When the player is not moving on the X-axis, the projectile works fine. But when the player is moving on the X-axis, the projectile does not move.

I have the rigidbody on the projectile with gravity off and frozen rotation on x, y, z and frozen position on y, z.

Is there a fix for the errors or is there a better way to do a projectile?

1 Answer

1

I think the code in the documentation is incorrect. Instantiate would not return a Rigidbody so you need to cast to this type in order to assign it to your clone variable.

clone = (Rigidbody)Instantiate(projectile, transform.position, transform.rotation);