Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by smems · Jan 03, 2016 at 05:57 PM · unity 5unity 2drigidbody2dwaypointmoveposition

How to use Rigidbody2D.MovePosition to move a kinematic object around looping waypoints?

Hello, I'm trying to make a gameObject move around a fixed set of waypoints continuously. I'm using Rigidbody2D.MovePosition to move the gameobject around the waypoints which works. But the object slows down when approaching a waypoint and stops for about 1 second and then starts to move to the next waypoint and it stops and this continues for all the waypoints. I tried to use AddForce to move the object but it doesn't move at all.

 void walk(){
             rb2d = GetComponent<Rigidbody2D>();
         // move towards the next waypoint
         Vector2 dir = (targetWayPoint.position - transform.position); //This gives me the direction of the next waypoint
              //i tried using AddForce and the object didn't move at all.
         //rb2d.AddForce(dir  * speed * Time.deltaTime);
         rb2d.MovePosition(new Vector2(transform.position.x,transform.position.y)  + dir * speed / 5 * Time.fixedDeltaTime);
             //I also tried:
            //rb2d.MovePosition(new Vector2(transform.position.x,transform.position.y)  + dir * speed / 5);
           //and also:
           //rb2d.MovePosition(new Vector2(transform.position.x,transform.position.y)  + dir * Time.fixedDeltaTime);
 
         if(transform.position == targetWayPoint.position) //if it reaches the waypoint
         {
             currentWayPoint ++ ;
             targetWayPoint = wayPointList[currentWayPoint];
             Debug.Log("Added the next waypoint(" + currentWayPoint + "). Object: " + gameObject.name);
         }
 
         if (currentWayPoint == wayPointList.Length-1) currentWayPoint = -1; //keep going around the waypoints
     }

If this kind of question was already answered please post the link. I couldn't find any question solving my problem.

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

1 Reply

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

Answer by OncaLupe · Jan 03, 2016 at 07:37 PM

Two things I see that are causing this:

You're aren't normalizing the 'dir' vector you get, so the closer to the target, the slower the speed.

You're testing equality to see if you reached the target, which is discouraged due to floats/vectors rarely being exactly equal.

Also, you should be storing the reference to the rigidbody instead of getting it every frame. GetComponent is a slow operation.

 using UnityEngine;
 using System.Collections;
 
 public class WaypointMover : MonoBehaviour
 {
     Rigidbody2D rb2d;
     public Transform[] wayPointList;
     Transform targetWayPoint;
     public float speed = 5f;
     int currentWayPoint = 0;
     public float arrivalDistance = 0.1f;
     float lastDistanceToTarget = 0f;
 
     void Awake()
     {
         //Store reference so it's not run every frame
         rb2d = GetComponent<Rigidbody2D>();
         //Get first waypoint
         targetWayPoint = wayPointList[currentWayPoint];
         lastDistanceToTarget = Vector3.Distance(transform.position, targetWayPoint.position);
     }
 
     void FixedUpdate()
     {
         walk();
     }
 
     void walk()
     {
         //If we're close to target, or overshot it, get next waypoint;
         float distanceToTarget = Vector3.Distance(transform.position, targetWayPoint.position);
         if((distanceToTarget < arrivalDistance) || (distanceToTarget > lastDistanceToTarget))
         {
             currentWayPoint++;
             if(currentWayPoint >= wayPointList.Length)
                 currentWayPoint = 0;
             targetWayPoint = wayPointList[currentWayPoint];
             lastDistanceToTarget = Vector3.Distance(transform.position, targetWayPoint.position);
             Debug.Log("Added the next waypoint(" + currentWayPoint + "). Object: " + gameObject.name);
         }else{
             lastDistanceToTarget = distanceToTarget;
         }
 
         //Get direction to the waypoint.
         //Normalize so it doesn't change with distance.
         Vector3 dir = (targetWayPoint.position - transform.position).normalized;
 
         //(speed * Time.fixedDeltaTime) makes the object move by 'speed' units per second, framerate independent
         rb2d.MovePosition(transform.position + dir * (speed * Time.fixedDeltaTime));
 
     }
 }

The movement is after the distance check, as MovePosition() doesn't take effect until the physics engine step near end of frame. Added an overshoot check so the object doesn't get stuck if arrivalDistance is smaller than movement amount.

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 smems · Jan 03, 2016 at 11:24 PM 0
Share

Thank you. This actually worked. I used .normalized but it messed it up and i thought i shouldn't use it. Now i actually understand what is does. Thanks again :)

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Rigidbody2D doesn't fall correctly when using MovePosition to move it horizontally 0 Answers

Stuck on using if else to prevent ball from getting stuck in brick breaker. very new to unity & C# :(,How would I reference an object to add onto its velocity in 2D? 1 Answer

HELP! RigidBody2D position is acting incredibly goofy!! 0 Answers

[HELP] 2D Ammo UI error wont count down shooting count and wont pick up and change ammo count 0 Answers

OnTriggerEnter2D called without collision 0 Answers


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