简体   繁体   中英

Projectile in Unity 2D

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

As @maZZZu said, Instantiate your projectile sprites ahead of your character so that your character and projectiles may not collide.

Secondly, clone.rigidbody2D.velocity = (clone.transform.forward * 1000); part of your code will only allow the projectile to move in forward direction (x-axis in case to 2D and z-axis in 3D). Try using mMovement instead (if you want it to move in other directions as well). eg clone.rigidbody2D.velocity = (mMovement * 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM