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 jamiecus · Jan 23, 2015 at 03:58 AM · 2danglevector

Rotating object to face mouse with physics isn't working

(First time on the forums) So, I want my players ship to face the mouse using physics and it sort of does... I have posted a screenshot below to illustrate the problem alt text

My code looks as follows:

 using UnityEngine;
 using System.Collections;
 
 public class Movement : MonoBehaviour {
 
     public GameObject thruster;
     
     public float thrust;
     public float torque;
     private float optimalDirection;
     
     public float mouseAngle;
     private float playerRotation;
 
     float angle;
 
     void Start() {
         rigidbody2D.centerOfMass = new Vector2(0.0f,0.0f);
     }
 
     void Update() {
     }
 
     // Update is called once per frame
     void FixedUpdate()
     {
 
         //Enables acceleration
         if ((Input.GetAxisRaw("Vertical") > 0) && (Input.GetKey("left shift")))
         {
             rigidbody2D.AddForce((transform.up * Time.deltaTime * thrust) * 1.5f, ForceMode2D.Force);
             thruster.particleEmitter.emit = true;
         }
         else if (Input.GetAxisRaw("Vertical") > 0)
         {
             rigidbody2D.AddForce(transform.up * Time.deltaTime * thrust, ForceMode2D.Force);
             thruster.particleEmitter.emit = true;
         }
         else
         {
             thruster.particleEmitter.emit = false;
         }
 
         //Allows ship to strave
         rigidbody2D.AddForce(transform.right * Time.deltaTime * (thrust / 2) * Input.GetAxisRaw("Horizontal"), ForceMode2D.Force);
 
         
         //Mouse rotation
         Vector2 mouse = Camera.main.ScreenToViewportPoint(Input.mousePosition);        //Mouse position
         Vector3 objpos = Camera.main.WorldToViewportPoint(transform.position);        //Object position on screen
         Vector2 relobjpos = new Vector2(objpos.x - 0.5f, objpos.y - 0.5f);              //Set coordinates relative to object
         Vector2 relmousepos = new Vector2(mouse.x - 0.5f, mouse.y - 0.5f) - relobjpos;
         mouseAngle = Vector2.Angle (Vector2.up, relmousepos);    //Angle calculation
         if (relmousepos.x > 0)
             mouseAngle = 360-mouseAngle;
 
         //sets 2 variables to aid with figuring out which direction to go
         playerRotation = rigidbody2D.rotation;
 
         //Finds the optimal direction
         optimalDirection = ((((mouseAngle - (playerRotation)) % 360) + 540) % 360) - 180;
 
 
         //Makes ships come to a stand still
         if (Mathf.Round(optimalDirection) == 0)
             rigidbody2D.rotation += optimalDirection;
 
         //Chages velocity when appropriate
         if (Mathf.Round(optimalDirection) > 0 && rigidbody2D.angularVelocity < -5)
             rigidbody2D.angularVelocity = rigidbody2D.angularVelocity / 1.5f;
         if (Mathf.Round(optimalDirection) < 0 && rigidbody2D.angularVelocity > 5)
             rigidbody2D.angularVelocity = rigidbody2D.angularVelocity / 1.5f;
 
         //Applying torque relative to Optimal_Direction
         if (Mathf.Round(optimalDirection) > 0)
             rigidbody2D.AddTorque(torque * Time.deltaTime);
         if (Mathf.Round(optimalDirection) < 0)
             rigidbody2D.AddTorque(-torque * Time.deltaTime);
 
 
     }
 }

I'm not sure what the issue is and was hoping for some sort of solution or alternative, the problem is reoccurring with every side however having the mouse at 90, 180, 270 and 360 degrees relative makes it align perfectly

i77cimgpsh-orig.png (202.4 kB)
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
0

Answer by carrollh · Jan 23, 2015 at 04:12 AM

EDIT: Fixed the code. This should work if you have a thing in the background with a collider on it.

I personally think you are doing waaaaay too much work. Look at Transform.LookAt You could just call it and be done. Lerp it if you want for the effects it looks like you're doing.

 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 RaycastHit hit;
 Physics.Raycast(ray, out hit);
 
 if (hit.collider != null)
 {
     if (hit.collider.tag == Tags.enemy) {
          transform.LookAt(hit.collider.transform.position);
     } else transform.LookAt(hit.point);
 }

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 carrollh · Jan 23, 2015 at 04:41 PM 0
Share

I'm glad it's working, but it still looks like a lot of code.

Also I just realized my code snippet will turn the object to face a thing with the enemy tag if clicked on, otherwise it will turn to point at the point on the background you clicked on.

avatar image jamiecus · Jan 23, 2015 at 05:42 PM 0
Share

It is quite bulky indeed, I will probably attempt to optimize it later on Thank you for replying :)

avatar image
0

Answer by jamiecus · Jan 23, 2015 at 03:39 PM

Transform.LookAt did not provide the desired effect however using the following worked //Finds the rotation of mouse Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; diff.Normalize(); mouseAngle = (Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg)-90;

         //sets 2 variables to aid with figuring out which direction to go
         playerRotation = rigidbody2D.rotation;
 
         //Finds the optimal direction
         optimalDirection = ((((mouseAngle - (playerRotation)) % 360) + 540) % 360) - 180;
 
         //Makes ships come to a stand still
         if (Mathf.Round(optimalDirection) == 0)
             rigidbody2D.rotation += optimalDirection;
 
         //Chages velocity when appropriate
         if (Mathf.Round(optimalDirection) > 0 && rigidbody2D.angularVelocity < -5)
             rigidbody2D.angularVelocity = rigidbody2D.angularVelocity / 1.5f;
         if (Mathf.Round(optimalDirection) < 0 && rigidbody2D.angularVelocity > 5)
             rigidbody2D.angularVelocity = rigidbody2D.angularVelocity / 1.5f;
 
         //Applying torque relative to Optimal_Direction
         if (Mathf.Round(optimalDirection) > 0)
             rigidbody2D.AddTorque(torque * Time.deltaTime);
         if (Mathf.Round(optimalDirection) < 0)
             rigidbody2D.AddTorque(-torque * Time.deltaTime);
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 Rtakasas · Apr 24, 2015 at 08:03 PM 0
Share

I am making a school project (Space game) with unity and I need to have rotation with physics. Sadly, this script is not working for me and modifications are not working. What I have noticed is that I am getting wrong mouseAngle. Also what you wanted to get with optimalDirection? Thanks in advance.

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Calculating the Angle between two vectors 2 Answers

Issues calculating angle in 2D 0 Answers

Finding the angle between 2 clicked points 2 Answers

Rotate so VectorY points to another Vector3 2 Answers

2D GunPivot Bug 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