• 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
Question by IgorUnity3D · Sep 16, 2016 at 11:13 AM · movementtransformrigidbody2daddforcetranslate

Best way to move a Rigidbody2D from point A to point B (Mouse Position)

We have the following scenario:

alt text

We would like to know what would be the best way to move a 'prefab(bullet)' with rigidbody from point A to point B. Since point B of the equation will always be the mouse position on the screen.

We have already tested use without a rigidbody (Transform.Translate) but we have problems with FPS depending on the frame rate that the user's machine can have.

Also already we tried some solutions found in the forum, but they did not help us much. Someone would have a simple solution to this case?

We just need the prefab trace a route from Point A to Point B using a given force (speed) and interpolating the movement.

Class attached to 'Bullet prefab':

 public class MovePrefab : MonoBehaviour
 {
     public Rigidbody2D rb2D;
 
     void Start()
     {
         rb2D = GetComponent<Rigidbody2D>();
         var mousePositionPointB = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
         rb2D.velocity = mousePositionPointB ;
 
     }
 }

Class attached to 'Turret':

 public class Turret : MonoBehaviour {
 
     public Transform pointA;
     public GameObject bulletPrefab;

     void Update () {
 
         if (Input.GetButtonDown("Jump"))
         {
             var pos = new Vector3(pointA.position.x, pointA.position.y);
             Instantiate(bulletPrefab, pos, pointA.rotation);
         }
         
     }
 }

This code does not work as it should, it can not draw a real route between points A and B.

Thanks in advance.

move-a-to-b.png (86.9 kB)
Comment

People who like this

0 Show 6
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 Sinnii · Sep 16, 2016 at 04:07 PM 1
Share

In your MovePrefab.Start(), try:

rb2D = GetComponent();

Vector3 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

Vector3 relativePos = mousePos - transform.position;

rb2D.velocity = relativePos.normalized * 1f; // 1f == desired speed

avatar image IgorUnity3D Sinnii · Sep 17, 2016 at 01:24 AM 0
Share

@Sinnii

Thank you so much man! This really seems to work ... we still need some more tests! I take a doubt, that necessarily serves the function "normalize" on relativePos.normalized? Could you explain?

avatar image Drakonno IgorUnity3D · Sep 17, 2016 at 01:28 AM 0
Share

Please, read about Time.deltaTime. It fixes FPS dependency and allows to use, for example, slow motion. :)

Vector.normalized is a vector divided by it's length. So it's always 1 unit length. Multiplying it by value, when it's the velocity vector, makes it move faster (bigger velocity vector is applied to it).

In the end, I'd recommend: Transform.Translate and Time.deltaTime

Show more comments

3 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Hanoble · Sep 17, 2016 at 04:27 AM

Something basic like this should work.

 public class Move : MonoBehaviour
 {
     public float moveSpeed;
     public Transform target = null;
 
     void Update()
     {
         if(target == null)
         {
             transform.localPosition += transform.forward * Time.deltaTime * moveSpeed;
         }
         else
         {
             transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
         }
     }
 }

If you are instantiating an object, then you need to instantiate it at your "shooting point" or wherever the bullet begins. When you instantiate the object you should set the target by getting this move component, or if it is already in your scene simply drag the target via the inspector. On instantiation you can also pass a starting rotation via a quaternion, or simply do look at after instantiation and let the move script Update() take it from there.

 transform.LookAt(target);
Comment

People who like this

0 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 IgorUnity3D · Sep 17, 2016 at 04:57 PM 0
Share

Right, but how to calculate object rotation? LookAt dont works

avatar image

Answer by Sinnii · Sep 17, 2016 at 05:52 PM

  public class MovePrefab : MonoBehaviour
  {

      static float speedPerSec = 1f;

      void Update()
      {
          transform.position = transform.position + transform.right * speedPerSec * Time.deltaTime;
      }
  }
 
  public class Turret : MonoBehaviour {
  
      public Transform pointA;
      public GameObject bulletPrefab;

      void Update () {
  
          if (Input.GetButtonDown("Jump"))
          {
              Instantiate(bulletPrefab, pointA.position, pointA.rotation);
          }
      }
  }
Comment

People who like this

0 Show 0 · 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

Answer by IgorUnity3D · Sep 18, 2016 at 01:40 PM

@Drakonno

It looks like there is reply nest limit. Sorry for not perfect code, it's really weird to write inside that editor in reply. Also, transform translate should fix the FPS problem if You multiply it by Time.deltatime. Like in:

  gameObject.transform.Translate(translationVector*speed*Time.deltaTime);

I can try this and pass feedback to you, but if I'm not mistaken already use Time.deltatime :\ (We will try!)

See: transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);

About this:

  void Update () {
        if (Input.GetButtonDown("Jump"))
        {
            var pos = new Vector3(firePoint.position.x, firePoint.position.y);
            var tmpObject = Instantiate(bullet, pos, bullet.transform.rotation) as Transform;
            tmpObject.LookAt(point);
        }
  }

I first store my created object in some kind of variable, then get it's component to use with LookAt.

In this case, i can set the "point" to my mouse position, right?

Thanks for the help so far!

Comment

People who like this

0 Show 0 · 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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

6 People are following this question.

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

Related Questions

How to find out magnitude of translation 1 Answer

AddForce from Two Sources 1 Answer

Tranform.translate does not have constant speed 1 Answer

move 2d character affected by physics with velocity and/or add force 2 Answers

AddForce transform.right not working correctly in 2d 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