Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 BDP1 · Apr 02, 2013 at 08:30 AM · mouse positionmouse cursor

Firing at mouse position, 2d game

Hello, I am writing my second question here in hopes for some guidance.

Currently I am working on a side scrolling game. I would like to be able to accurately fire at the mouse cursor on screen. I have attached a script to my "gun" on my player's ship that will aim at the mouse pointer however it is not accurate. The current script just changes where the gun points based on mouse input and will not react to the actual mouse position.

An example...ship is at top left of the screen, mouse is pointing at the middle of the screen. If the ship is moved down while the mouse cursor remains in the center of the screen, the gun will not look at the mouse cursor. I would like the script to always have the gun look at the mouse pointer.

I imagine the solution involves drawing a ray from the camera to the mouse position in world space, getting the Vector3 coords of that RaycastHit and storing it. However this is where I get lost. I'm not sure how to rotate an object to look at a Vector3 coordinate. I have seen the Transform.LookAt function and feel my answer lies there, but is it that simple?

 var minimumY : float = -60;
 var maximumY : float = 60;
  
 var rotationY : float = 0;
  
 var originalRotation : Quaternion;
 
 static var rapidFire : boolean = false;
 
 var bullet : Rigidbody;
 var rapidfireBullet : Rigidbody;
 var specialBullet : Rigidbody;
 var explosion : Transform;
 
 function Update(){
     rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
     rotationY = ClampAngle (rotationY, minimumY, maximumY);
     yQuaternion = Quaternion.AngleAxis (rotationY, Vector3.forward);
     transform.localRotation = originalRotation * yQuaternion;
     
     //looks to see if left mouse button is prssed, if it is, fires a bullet
     if(Input.GetMouseButtonDown(0)){
         if(rapidFire == true){
             StartCoroutine(RapidfireTimer());
             var rapidfiretempBullet : Rigidbody;            
             rapidfiretempBullet = Instantiate(rapidfireBullet, transform.position, transform.rotation);
         }
         
         var tempBullet : Rigidbody;            
         tempBullet = Instantiate(bullet, transform.position, transform.rotation);
     }
     
     //right click for special attack
     if(Input.GetMouseButtonDown(1)){
         if(playerScript.playerFormPoints > 10){
             var tempSpecialBullet : Rigidbody;
 
             tempSpecialBullet = Instantiate(specialBullet, transform.position, transform.rotation);
             playerScript.playerFormPoints -= 3;
         }
     }
 }
  
 function Start(){
     if(rigidbody){
         rigidbody.freezeRotation = true;
     }
     originalRotation = transform.localRotation;
 }
 
 function RapidfireTimer(){
     
     yield new WaitForSeconds(10);
     rapidFire = false;
     Debug.Log("Rapid Fire is false");
 }
   
 function ClampAngle (angle : float, min : float, max : float){
     if(angle < -360){
         angle += 360;
     }
     if(angle > 360){
         angle -= 360;
     }
     return Mathf.Clamp(angle, min, max);
 }
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 cdrandin · Apr 02, 2013 at 08:49 AM 1
Share

If you want the gun to follow the position of your cursor you will need to use Atan2

http://sinepost.wordpress.com/2012/02/16/theyve-got-atan-you-want-atan2/

Gives you what you need for your initial point(gun) to your destination point(cursor).

2 Replies

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

Answer by LyanApps · Apr 02, 2013 at 08:01 PM

Are you moving the camera position as well?

You can use Input.mousePosition to get the location of your mouse on each frame. http://docs.unity3d.com/Documentation/ScriptReference/Input-mousePosition.html

 var relative = gun.position - Input.mousePosition;
 gun.rotation = Quaternion.Euler(0,0, Mathf.Atan2(relative.y, relative.x) * Mathf.Rad2Deg);

You'll have to align your coordinate systems with this though. http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Atan2.html

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
avatar image
1

Answer by BDP1 · Apr 02, 2013 at 09:56 PM

Thank YOU!

This code works perfectly!!

 function Update () {
     var mousePos = Input.mousePosition;
     mousePos.z = 32; //The distance from the camera to the player object
     var lookPos : Vector3 = Camera.main.ScreenToWorldPoint(mousePos);
     lookPos = lookPos - transform.position;
     var angle : float = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
     transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
 
 }

Wish I searched a little harder because this has been asked before!

Comment
Add comment · Show 1 · 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 Shinugami · Nov 25, 2013 at 04:01 PM 0
Share

Thankyou, exactly what i was looking for. I had to add +90 to my angle before setting the transform.rotation but it works.

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

12 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

Related Questions

Lock Cursor to Screen resolution 1 Answer

Stop pulling an object when it hits a collider 1 Answer

Unity 2d Top-Down Mouse Aiming Stutters When Moving 2 Answers

Continuously rotating horizontally a player with the mouse position 1 Answer

Combine animation and mouse position 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