Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
0
Question by nichos1 · May 20, 2014 at 03:46 PM · movementunity 2dmousemove an object

Unity 2D: move towards mouse and through mouse

Hi, I am a noob, and I have looked everywhere for a script that moves a bullet(or object) towards the mouse and through the mouse position. My game is a 2D top down shooter using the x and y coordinates(basically no gravity). Can anyone point me in the right direction to make my bullets move this way.

Comment
Add comment · Show 1
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 supernat · May 20, 2014 at 03:57 PM 0
Share

First, just a general question. Do you have an overall strategy, i.e. once the bullet is in motion, how do you plan to detect if the bullet hit its target? This is going to be much more complicated that just moving the bullet.

You say you are a noob, so I'll just suggest starting with some tutorials on basic coordinate systems, game object movement, and scripting, but beyond that you'll have to handle user interaction (click a button to fire the bullet), camera interaction (transform the mouse click from screen space to world space), ray casting (to deter$$anonymous$$e what is in the way of the bullet), object rotations, and script management. I understand you want to just jump in and start having fun, but there is a large amount of work/knowledge involved even for a simple thing, sorry, but I would highly recommend the tutorials first. If you search google or even Unity Answers though, there are plenty of scripts available that move objects. Did you look at the "Related Questions" on the right side of this page? There are several that look similar. Good luck, and have fun!

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by robertbu · May 20, 2014 at 03:54 PM

Here is the basic code. You need to have a 'prefab' game object variable at the top of the file and an 'amount' variable that defines how much force to apply. Start with 'amount' set to 500, then adjust. Note your sprite should have the forward of your bullet facing right when the rotations is (0,0,0).

 var pos = Camera.main.WorldToScreenPoint(transform.position);
 var dir = Input.mousePosition - pos;
 var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
 var rotation = Quaternion.AngleAxis(angle, Vector3.forward); 
 var go = Instantiate(prefab, transform.position, rotation);
 go.rigidbody2D.AddForce(transform.right * amount);
Comment
Add comment · Show 7 · 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 nichos1 · May 20, 2014 at 04:09 PM 0
Share

For some reason, unity is not detection rotation as anything, do you know the issue? And also, I'm assu$$anonymous$$g I put this in an update function.

avatar image robertbu · May 20, 2014 at 04:35 PM 0
Share

There should have been a 'var' in front of 'rotation'. Note this code assumes your bullets have a Rigidbody2D. You're not trying to move them through the Transform are you?

avatar image nichos1 · May 20, 2014 at 05:22 PM 0
Share

$$anonymous$$y bullets have a rigid body,and whenever I click it creates a new prefab at my players location. Code for clicking:

 var thePrefab : GameObject;
 
 function Update () {
 
     if(Input.GetButtonUp("Fire1")){
         
         if($$anonymous$$anaBar.mp > 20){
         $$anonymous$$anaBar.mp -= 20;
         Instantiate(thePrefab,transform.position, transform.rotation);
         //var instance : GameObject = 
         }
     }

Code that you gave me:

 var prefab : GameObject;
 var amount : float;
 var Timer : float;
 var Timer$$anonymous$$ax : float;
 
 function Start () {
 Timer$$anonymous$$ax = 500;
 
 }
 
 function Update () { 
     var pos = Camera.main.WorldToScreenPoint(transform.position);
     var dir = Input.mousePosition - pos;
     var angle = $$anonymous$$athf.Atan2(dir.y, dir.x) * $$anonymous$$athf.Rad2Deg;
     var rotation = Quaternion.AngleAxis(angle, Vector3.forward); 
     var go = Instantiate(prefab, transform.position, rotation);
     go.rigidbody2D.AddForce(transform.right * amount);
     
     
     Timer += 1;    
         
     if(Timer == Timer$$anonymous$$ax){
         Destroy(gameObject);
     }
 
 
 }
 function OnCollisionStay2D(coll: Collision2D) {
 
      
      if(coll.gameObject.name == "Enemy"){
          Destroy(gameObject);
           
      }
      if(coll.gameObject.name == "Wall"){
          Destroy(gameObject);
           
      }
 }

For some odd reason, whenever I click the game is creating a thousand bullets, to the point of my program crashing. what am I doing wrong?

avatar image robertbu · May 20, 2014 at 05:25 PM 0
Share

The code I gave you goes into your first function, not in the bullet code. Something like:

 var thePrefab : GameObject;
 var amount : float = 500.0;
 
 function Update () {
 
    if(Input.GetButtonUp("Fire1")){
 
        if($$anonymous$$anaBar.mp > 20){
            $$anonymous$$anaBar.mp -= 20;
            var pos =  Camera.main.WorldToScreenPoint(transform.position);
            var dir = Input.mousePosition - pos;
            var angle = $$anonymous$$athf.Atan2(dir.y, dir.x) * $$anonymous$$athf.Rad2Deg;
            var rotation = Quaternion.AngleAxis(angle, Vector3.forward); 
            var go = Instantiate(prefab, transform.position, rotation);
           go.rigidbody2D.AddForce(transform.right * amount);
        }
     }
 }
 
avatar image nichos1 · May 20, 2014 at 05:45 PM 0
Share

the script now works. However, the bullets only shoot to the right ins$$anonymous$$d of all 4 directions. Is there a quick fix to this? I am using the x and y coordinates.

Show more comments

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

21 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

Related Questions

Moving an object on the X axis corresponding to mouse movment 0 Answers

2D: How to make Gradius III with a mouse? 1 Answer

Detect Mouse Movement 1 Answer

OnMouseUp() Click Display Effect. 1 Answer

Move speed decrease stoping object problem. 1 Answer


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