I'm attempting to learn Unity (so please forgive my newbie-ness). I've set up my project as 2d, got a sprite moving about and I'm trying to get a projectile firing (I appreciate there are MANY SO q's about such, but I just can't get it to work, after trying many solutions). I'm a complete nub when it comes to physics!
Here's my very simple script:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public Transform mObject;
public Transform mProjectile;
public Vector2 mProjectileSpeed = new Vector2 (10f, 10f);
public Vector2 mSpeed = new Vector2(15, 15);
private Vector2 mMovement;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float inputX = Input.GetAxis("X");
float inputY = Input.GetAxis("Y");
mMovement = new Vector2 (mSpeed.x * inputX, mSpeed.y * inputY);
if (Input.GetButton ("Fire1"))
Shoot ();
}
void Shoot(){
GameObject clone = (GameObject)Instantiate (mProjectile, rigidbody2D.transform.position, Quaternion.identity);
clone.rigidbody2D.velocity = (clone.transform.forward * 1000);
}
void FixedUpdate(){
rigidbody2D.velocity = mMovement;
}
}
And this is what it's doing:
No force is being added to the instantiated object and it shoots out both sides of my sprite, which I just don't understand at all.
I did find a solution on the Unity answers site that said to IgnoreCollider
just in case the two box colliders were conflicting results, but it didn't make a difference.
I'm sure I'm doing something completely stupid, but how can I do this?
Many thanks!
Try using Addforce() method, something like this :
gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime);
or
gameObj.rigidbody2D.AddForce(transform.forward * 100);
or
gameObj.rigidbody2D.AddForce(Vector3.up * 1000);
See which combination and what values matches your requirement and use accordingly. Hope it helps