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 /
avatar image
0
Question by unity_005848358 · Aug 19, 2018 at 12:49 AM · scripting problemscripting beginner

Make an object a certain distance from me.

Hello so I have finally got some code working that enables an object to rotate and move towards another object when space bar is pressed. So an object will move to the player when space bar is pressed. Awesome, got that running! however it moves so freakin close to the player! I want it to move a little bit away from the player. Not to close, how can I do that. Here is my code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 
 public class lerpFinal : MonoBehaviour
 {
     //This is a new variable to store a Vector3 Position
     private Vector3 newPosition;
     private bool flagPos;
     public Transform Player;
     public Transform Target; 
 
     //Here we set the current position of the object using transform.position
     private void Awake()
     {
         newPosition = transform.position;
     }
 
     //Here we are running positionChanging function in each framej
     void Update()
     {
         PositionChanging();
         transform.LookAt(Target); 
     }
 
     void PositionChanging()
     {
         //Here is Where the positions are set
         Vector3 positionA = new Vector3(0, 0, 0);
         Vector3 positionB = Player.position;
 
         //Inputing the following keys will allow us to Change the Position
         if (Input.GetKeyDown(KeyCode.Space) && flagPos == false)
         {
             newPosition = positionA;
             flagPos = true;
 
         }
         else if (Input.GetKeyDown(KeyCode.Space) && flagPos == true)
         {
             newPosition = positionB;
             flagPos = false;
         }
       
 
         transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime);
     }
 }
 


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 unity_005848358 · Aug 19, 2018 at 06:56 AM 0
Share

You guys are awesome, thank you so much.

2 Replies

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

Answer by rainChu · Aug 19, 2018 at 01:26 AM

I think I see what you're trying to do. Instead of Lerping towards the player's actual position, you should find a new position that's close to the player, along a line of sight.

Try this adding this to the bottom of PositionChanging():

 void PositionChanging()
 {
     // ... Original Code as above ....
     
     // Find the amount we have to move in total
     var offset = transform.position - newPosition;

     // Find the direction we have to move in
     var direction = offset.normalized;

     // Add 0.3 units to the newPosition, away from the player
     newPosition += direction * 0.3f;

     // ... Original Code as below ....

     // Now you lerp
     transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime);
 }
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 oStaiko · Aug 19, 2018 at 02:44 AM

The exact solution here depends on how your game plays, as in is it on a 2D field, 3D, etc, but here's a generic solution you can modify to fit your needs:


 public float dist = 3; // How far to stop (meters)
 public float speed = 1; // How fast to follow (m/s)
 public Transform player; // Reference to player
 protected Vector3 targetPosition = Vector3.zero;
 private bool isFollowing = false;
 [SerializeField]
 private bool debug = false;
 
 void Update ()
 {
     if (isFollowing)
     {
         transform.LookAt (player);
         float dist3 = speed*Time.deltaTime; // How far to move this frame
         float dist2 = Vector3.Distance (targetPosition, transform.position); // Distance from target
         if (dist3>dist2)
         {
             dist3 = dist2;
             isFollowing = false; // At target, stop following. (Optional! Remove to follow forever)
             if (debug) Debug.Log("Reached target!");
         }
         Vector3 direction = (targetPosition-transform.position).normalized;
         transform.position += direction*dist3; // This moves the object each frame.
     }
 
     if (Input.GetKeyDown(KeyCode.Space) && !isfollowing)
     {
         Follow ();
     }
     else if (Input.GetKeyDown(KeyCode.Space) && isfollowing)
     {
         StopFollow ();
     }
 }
 
 
 void Follow ()
 {
     if (debug) Debug.Log("Follow() called");
     float dist2 = Vector3.Distance (player.position, transform.position); // Distance from player
     
     if (dist2 >= dist ) // Don't do anything if its already in range
     {
         isFollowing = true;
         float frac = 1 - (dist/dist2); // How far to travel, converts distances to a fraction
         Vector3 targetPosition = Vector3.Lerp (transform.position, player.position, frac); // Gets position in straight line
     if (debug) Debug.Log("New target:\n" + targetPosition.ToString());
     }
     else
     {
         if (debug) Debug.Log("Follow Cancled!\nAlready in range of target!");
         StopFollow ();
     }
 }
 
 void StopFollow ()
 {
     if (debug) Debug.Log("StopFollow() Called");
     targetPosition = Vector3.zero // Not necessary, but can be nice to have for debugs
     isFollowing = false;
 }



Replace your script with this, it should do what you need, and a lot better than what you currently have. I didn't test it myself, so you just leave a comment if there's any errors you cant fix on your own.

As a side note, you really botched Vector3.Lerp(). Its a somewhat common mistake where it kinda works right, but you should really look in to the proper usage for it. Your usage makes the game play VERY differently and high and low FPS differences.

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 rainChu · Aug 19, 2018 at 02:47 AM 0
Share

Good catch on Vector3.Lerp. I agree that it has a huge impact on consistency when used in that way. In production games it shouldn't be used like that. But I feel it does a decent enough approximation of an ease out function for prototypes, so I don't $$anonymous$$d seeing it used like this.

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

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

Object not responding to OnTriggerEnter() 2 Answers

Slowly increase motor.force 1 Answer

Rotation question. 1 Answer

Player Prefs Dosen't work on android 0 Answers

Im having trouble using different scriptable objects in a script 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