• 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 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
Add comment · 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 $$anonymous$$ovePrefab.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. $$anonymous$$ultiplying 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
0

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

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

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

avatar image
0

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
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

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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



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 have a GameObject follow a path with c#? 3 Answers

How to find out magnitude of translation 1 Answer

Wait a fraction of a second within a Function Update() 1 Answer

How can i synchronize prefab with NetworkTranform? 1 Answer

Rotatating a character 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges