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 CharlieBoots · Mar 19, 2016 at 05:02 PM · c#2d gameshootingmouseposition

Shooting bullets in mouse direction for 2D game

I am working on a top down game where the player can shoot bullets by aiming with his mouse. However, I am quite new to programming and am having a bit of trouble figuring out how to do so. My bullet prefab has this code on it:

     public float speed;

 public PlayerController player;

 public GameObject enemyDeathEffect;

 public GameObject impactEffect;

 // Use this for initialization
 void Start () {
     player = FindObjectOfType<PlayerController> ();

     if (player.transform.localScale.x < 0)
         speed = -speed;
 }
 
 // Update is called once per frame
 void Update () {



     GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, speed);

 }

 void OnTriggerEnter2D(Collider2D other) {

     if (other.tag == "Enemy") {
         Destroy (other.gameObject);
         //Instantiate (enemyDeathEffect, other.transform.position, other.transform.rotation);
 

     }

     //Instantiate(impactEffect, other.transform.position, other.transform.rotation);

     if (other.name == "player") {
         return;
     }

     Destroy (gameObject);

     }

     

}

I instantiate the bullet using my player controller script. On it, I have a GameObject variable called firePoint, which is an empty GameObject situated at the center of my player sprite. I also have a GameObject variable in which I drag the prefab of my bullet for the player to access.

For now, the bullet goes upwards.

public Transform firePoint; public GameObject friendlyBullet;

 public bool hasGun;

 public bool savedAnn;

 public int memoriesCollected;

 public bool nextToAnn;
 public bool nextToMemory;

 public bool memoryExists;





 // Use this for initialization
 void Start () {
     
     playerBody = this.gameObject.GetComponent<Rigidbody2D> ();
 
 }
 
 
 // Update is called once per frame
 void Update () {


     //go right
     if (Input.GetKey (KeyCode.D)) {
         playerBody.AddForce(new Vector2 (speed, 0));
         //transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
     }

     //go left
     if (Input.GetKey (KeyCode.A)){
         playerBody.AddForce(new Vector2 (-speed, 0));
         //transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
     }

     //go up
     if (Input.GetKey (KeyCode.W)){
         playerBody.AddForce(new Vector2 (0, speed));
     
         //transform.position += new Vector3 (0.0f,speed * Time.deltaTime, 0.0f);
     }

     //go up
     if (Input.GetKey (KeyCode.S)){
         playerBody.AddForce(new Vector2 (0, -speed));
     
         //transform.position -= new Vector3 (0.0f,speed * Time.deltaTime, 0.0f);

} if (Input.GetKeyDown (KeyCode.Space) && (hasGun) ) {

         Instantiate (friendlyBullet, firePoint.position, firePoint.rotation);

     } 
     
     
 }


Any pointers as to where to integrate the mouse position would be greatly appreciated!

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Jason2014 · Mar 19, 2016 at 10:19 PM

 var Rotation : Quaternion = Quaternion.LookRotation (transform.position - Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector3.forward);    
 
 transform.rotation = Rotation;
 transform.eulerAngles = Vector3 (0, 0, transform.eulerAngles.z);

This works perfectly for aiming by mouse. Insert it in FixedUpdate function at start.

Additionally let me share you some another tips. Firstly, NEVER use GetComponent in Update function! Update function do instructions 60 frames per second, so you are getting access to the same component 60 times per second. Much better is to insert component to variable as reference and then access it in Awake or Start (Awake do instructions once even when script is disabled, but Start do instructions once when script IS enabled). Secondly you can define movement by AddForce much simpler. Look at this:

 PlayerRigidbody2D.AddForce (Vector2 (Input.GetAxis ("Horizontal") * MovementSpeed, Input.GetAxis ("Vertical") * MovementSpeed));

And the last advice. All code defining physics insert in FixedUpdate function. It works as normal Update, but it is counted by "fixed rate". See documentation for further details.

Comment
Add comment · Show 2 · 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 CharlieBoots · Mar 21, 2016 at 12:51 AM 0
Share

Hi! First off, thank you for your suggestion and advice. I just had some concerns about the 'var' and ':' sign in the code. Both are seen as errors in my script. If I'm correct, these do not work in c#, but it may be something else entirely. Here is what it looks like:

void FixedUpdate () {

     var Rotation : Quaternion = Quaternion.LookRotation (transform.position - Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector3.forward);

     transform.rotation = Rotation;
     transform.eulerAngles = Vector3 (0, 0, transform.eulerAngles.z);

 }
avatar image Jason2014 CharlieBoots · Mar 21, 2016 at 07:30 PM 0
Share

Of course, sorry for this mistake. You're right, I'm currently using UnityScript. I didn't noticed you are using C#. Looks like this:

Quaternion Rotation = Quaternion.LookRotation (transform.position - Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector3.forward);

But I assume you will get error for assigning value to transform.rotation. Unfortunately, C# doesn't allow to change values directly, you have to use "temporary variables". You have to first declare at start transform.rotation in a variable for example: private Quaternion playerRotation and then assign value in Start function. Same thing as eulerAngles. You can try as I wrote earlier, but I'm was using C# and I know it usually throws an error, while trying to change value directly. Sorry again for mistake!

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

129 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

how do i make my immovable 'empty gameobject spawnpoint' shoot bullets in the direction of my crosshair? 0 Answers

2d Shooting to Mouse position 0 Answers

Z position moving in 2D space 1 Answer

Player follows mouse, but I need only Y 1 Answer

(Help) I am having trouble with creating a simple 2D game in Unity. Please help. :) 0 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