Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Daniel_Zabojca · Oct 15, 2015 at 12:42 PM · c#2d game2d-platformer

2D Unity 5.1 shooting a bullet in the direction my player is facing.

Hello there,

I wanted to make a 2d top down game where if you press left mouse button 1, then you will shoot a bullet. the problem is that the bullet is spawned in the middle of the player and it does not even fly in a direction. Here is my player script :

        using UnityEngine;
        using System.Collections;

       public class PlayerMovement2 : MonoBehaviour {
 Rigidbody2D PlayerBody;
 Animator Animi;


 // Use this for initialization
 void Start () {
     PlayerBody = GetComponent<Rigidbody2D>();
     Animi = GetComponent<Animator>();



 }
 
 // Update is called once per frame
 void Update () {
     
     Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

     if (movement_vector != Vector2.zero)
     {
         Animi.SetBool("Walking", true);
         Animi.SetFloat("Input_x", movement_vector.x);
         Animi.SetFloat("Input_y", movement_vector.y);
     }
     else
     {
         Animi.SetBool("Walking", false);
     }
     PlayerBody.MovePosition(PlayerBody.position + movement_vector * Time.deltaTime);
 }

}

and here is my bullet script :

                   using UnityEngine;
                   using System.Collections;
                   public class BulletPrototype1 : MonoBehaviour
                  {
                    public float maxSpeed = 25f;
                   public Rigidbody2D bullet;
                    void Update()
                 {
                    if (Input.GetButtonDown("Fire1"))
                  {
                          Rigidbody2D bulletInstance = Instantiate(bullet, transform.position,                         Quaternion.Euler(new Vector3(0, 0, 1))) as Rigidbody2D;

         bulletInstance.velocity = transform.forward * maxSpeed;

     }
 }

}

I really do not see the problem. Can someone explain the problem to me, and maybe give an example about how it should be done? I am thinking it is something with the variable and the transform.forward, but i can be wrong about that.

Thank you in advance, Daniel.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Erdroy · Oct 15, 2015 at 04:24 PM

@Daniel_Zabojca

There is a problem with collision. Try to ignore collision between player and bullet. You should use this: http://docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html

 if (Input.GetButtonDown("Fire1"))
 {
    Rigidbody2D bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0, 0, 1))) as Rigidbody2D;
     bulletInstance.velocity = transform.forward * maxSpeed;
 
     Physics2D.IgnoreCollision(bulletInstance.GetComponent<Collider2D>(),  GetComponent<Collider2D>());
 }

Also you can set the rotation when instantiating to current player rotation. (Quaternion.Euler(new Vector3(0, 0, 1)) to transform.rotation, or just zeroe' this with: Quaternion.identity)

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Daniel_Zabojca · Oct 16, 2015 at 07:24 AM 0
Share

So, if I use Quaternion.euler(new Vector3(0,0,1)) it won't be set like I will, but using transform.rotation will? Also, I changed (Quaternion.Euler(new Vector3(0, 0, 1)) to transform.rotation but i still get the problem that the ball does not fly automatically when it spawns, so I have to "walk" against it to make it move in the opposite direction. Did I do something wrong with the ignore collision? Because I have a collider on the bullet, and a collider on the player (Both are 2D) and I think it has something to do with it. (correct me if I am wrong about it.) Also, it gets cloned, but I will fix that later.

I have another question : If I zero it with Quaternion.identity, will it increase performance or decrease loading time? because how I see it now it will shorten the script, but that gets me curious about what would happen if I would use transform.rotation ins$$anonymous$$d. So long story short : What is the difference when i use Quaternion.identity and Transform.rotation? What is the difference in use?

Thank you again for helping me, And have a nice day, $$anonymous$$.

avatar image Erdroy Daniel_Zabojca · Oct 16, 2015 at 02:06 PM 0
Share

1) $$anonymous$$aybe bulletInstance.AddForce(transform.forward * maxSpeed); will work? But .velocity should work too...

2) Quaternion.identity makes new Quaternion: from source code: return new Quaternion(0.0f, 0.0f, 0.0f, 0.0f); it using the 'new' keyword, so it taking some memory and Garbage Collector has more work to do(I think it is like this, I really don't know how .NET/$$anonymous$$ono work with 'new' and structs I'm more familiar with C/C++).

Using 'trasform' can be a little bit slow(It goes from the wrapper), so the best solution there - is to make a reference at Start(), eg.:

 private Transform _myTransform;
 private void Start()
 {
      _myTransform = transform;
 }

And then, use _myTransform.rotation, _myTransform.position etc. ins$$anonymous$$d of transform.position.

avatar image Daniel_Zabojca Erdroy · Oct 18, 2015 at 07:39 AM 0
Share

First, thank you for trying to help me. Second, It still does not work, I think I did something wrong again, so here is the script:

       using UnityEngine;
       using System.Collections;
       public class BulletPrototype1 : $$anonymous$$onoBehaviour

{

 public float maxSpeed = 25f;
 public Rigidbody2D bullet;
 private Transform _myTransform;
 private void Start()
 {
     _myTransform = transform;
 }

 void Update()
 {
     if (Input.GetButtonDown("Fire1"))
     {
         Rigidbody2D bulletInstance = Instantiate(bullet, transform.position, transform.rotation) as Rigidbody2D;
         bulletInstance.AddForce(transform.forward * maxSpeed);

         Physics2D.IgnoreCollision(bulletInstance.GetComponent<Collider2D>(), GetComponent<Collider2D>());
     }

} }

Can you tell me what I did wrong this time? the bullet still does not want to fly, so I literally have to drive against the bullet to make it move. Thank you in advance, and have a nice day, $$anonymous$$.

Show more comments
avatar image
2

Answer by mnmwert · Jun 19, 2016 at 07:31 PM

Here is a script that spawns and fires a bullet. I used it for my 2D top down space shooter game i'm making.

using UnityEngine; using System.Collections;

public class ProjectileSpawn : MonoBehaviour { public GameObject Projectile; private GameObject cloneProj; public float fireSpeed; public float fireRate; public Transform Player; public float speed; public Vector3 target; public Transform target1;

 void Start ()
 {
     target = target1.transform.position;
     
      
     transform.rotation = Player.transform.rotation;
 }
 
 
 void Update ()
 {
    
     transform.rotation = Player.transform.rotation;
     if (Input.GetKey(KeyCode.Mouse0) && Time.time > fireRate)
     {
         fireRate = Time.time + fireSpeed;
         cloneProj = (GameObject)Instantiate(Projectile, transform.position, transform.rotation);
         target = target1.transform.position;
         
         
     }

     var delta = speed * Time.deltaTime;
     cloneProj.transform.position = Vector3.MoveTowards(cloneProj.transform.position, target, delta);
     if (cloneProj.transform.position == target)
     {
         Destroy(cloneProj.gameObject);
     }

 }

}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Cannot delay player respawn. 2 Answers

Unity 2D : C# : Animation : CS1061 : Animation does not contain definition for SetFloat.. 1 Answer

C# delaying command 0 Answers

Values not updating in Unity. - UPDATED 1 Answer

Detect whether a Rigidbody collided with a Trigger 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges