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 sakibmd6222 · May 23, 2018 at 05:34 PM · objecttransform.positionmovemouseclickonmousedown

How to move object to the position of another object while clicked on it?

Suppose, I have three objects A, B, C and a game object G. I want to move object G to the position of B when I click on object B. Similarly I want to move object G from position of B to the position of A when click on object A. Similarly I want to move object G from position of A to the position of C when click on object C. I tried but it works for only one object I included to the game object script. Suppose I included object B to the game object script. So the game object G only goes to the position of object B. Here's the code,

// this script is used in game object

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Player : MonoBehaviour { public GameObject midPoint;

 public float speed;
 private bool move = false;

 private Vector2 pathTarget;

 void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         Renderer render = midPoint.GetComponent<Renderer>();

         if (render.enabled == true)
         {
             if (move == false)
             {
                 move = true;
             }
         }
         pathTarget = midPoint.transform.position;
     }
     if (move == true)
     {
         transform.position = Vector2.MoveTowards(transform.position, pathTarget, speed * Time.deltaTime);
     }
 }

}

// I used this script for each of the three objects A, B, C

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class PathPoint : MonoBehaviour {

 public void OnMouseDown()
 {
     Renderer pRender = this.gameObject.GetComponent<Renderer>();

     if (pRender.enabled == false)
     {
         pRender.enabled = true;
     }
 }

}

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 Tobychappell · May 23, 2018 at 06:09 PM 0
Share

So you'd like to be able to select a gameobject, and tell it to move to another gameobject?

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Tobychappell · May 23, 2018 at 09:13 PM

A couple classes i knocked up, haven't tested them but they should do the trick with minor changes.


CharacterPointer

Place this on the camera

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;
     
     [RequireComponent(typeof(Camera))]
     public class CharacterPointer : MonoBehaviour
     {
       public LayerMask physicsLayer;
       
       public float maxDistance;
       public QueryTriggerInteraction triggerInteraction;
     
       public RaycastHit2D[] hits = new RaycastHit2D[16];
       private int hitCount;
     
       private Transform tran;
       private Camera viewport;
     
       private Character selectedCharacter;
       private bool leftClick;
       private bool rightClik;
     
       private void Awake()
       {
         tran = transform;
         viewport = GetComponent<Camera>();
       }
     
       private void Update()
       {
         leftClick = Input.GetMouseButtonDown(0);
         rightClik = Input.GetMouseButtonDown(1);
     
         if (leftClick || rightClik) // Need to find the objects underneath the cursor
         {
           var ray3D = GetRay();
           Vector2 mousePosition2D = new Vector2(ray3D.origin.x, ray3D.origin.y);
           hitCount = Physics2D.RaycastNonAlloc(mousePosition2D, Vector2.zero, hits, maxDistance, physicsLayer);
         }
     
         if (leftClick) // LeftClick takes priority if both were pressed
         {
           if (hitCount == 0) // Nothing was selected
           {
             if (selectedCharacter != null)
             {
               selectedCharacter.Deselect();
               selectedCharacter = null;
             }
           }
           else
           {
             // #### Checking if we clicked on a character
             Character newCharacter = GetComponentFromHits<Character>();
     
             if (newCharacter == null) // If we didn't select a new character
             {
               if (selectedCharacter != null) // Deselect current character if present
               {
                 selectedCharacter.Deselect();
                 selectedCharacter = null;
               }
             }
             else // if we did select a new character
             {
               // If we selected a character that was not our current character
               if (newCharacter != selectedCharacter)
               {
                 if (selectedCharacter != null) // Deselect current character if present
                 {
                   selectedCharacter.Deselect();
                   selectedCharacter = null;
                 }
               }
     
               selectedCharacter = newCharacter;
               selectedCharacter.Select();
             }
           }
         }
         else if (rightClik && selectedCharacter != null && hitCount > 0) // If we have a character selected and right click was pressed and at least 1 thing was hit
         {
           PathPoint selectedPoint = GetComponentFromHits<PathPoint>();
     
           if (selectedPoint != null && selectedCharacter.MyPathPoint != selectedPoint) // If a PathPoint was found that was not on the same gameobject as the character
           {
             selectedCharacter.SetTarget(selectedPoint, true, Input.GetKey(KeyCode.LeftShift));
           }
         }
       }
     
       /// <summary>
       /// Attempts to get the first object of type T from the collection of hits, will return null if none found.
       /// </summary>
       /// <typeparam name="T">The Type to search for</typeparam>
       /// <returns></returns>
       private T GetComponentFromHits<T>() where T : new()
       {
         T temp = default(T);
         for (int i = 0; i < hitCount; i++)
         {
           temp = hits[i].transform.GetComponent<T>();
           if (temp != null)
           {
             break;
           }
         }
         return temp;
       }
     
       private Ray GetRay()
       {
         Vector3 mousePos = Input.mousePosition; // Assuming that the game is fullscreen
         return viewport.ScreenPointToRay(mousePos);
       }
     }




PathPoint

Place this on the gameobjects that have a collider and a renderer that you want to use as a point to send characters to. A PathPoint's renderer will become enabled if one or more characters are moving towards said PathPoint.

     [RequireComponent(typeof(Renderer))]
     public class PathPoint : MonoBehaviour
     {
       public bool startingState;
       private Renderer myRenderer;
       private Transform tran;
       public int CharactersMovingTowards { get; private set; }
     
       public Vector3 Position
       {
         get
         {
           return tran.position;
         }
       }
     
       private void Awake()
       {
         tran = transform;
         myRenderer = GetComponent<Renderer>();
         SetPathState(startingState);
       }
     
       /// <summary>
       /// Enables / Disables the Renderer attached to this PathPoint
       /// </summary>
       /// <param name="nState"></param>
       public void SetPathState(bool nState)
       {
         myRenderer.enabled = nState;
       }
     
       public void CharacterOnPath(bool onPath)
       {
         CharactersMovingTowards += onPath ? 1 : -1;
         SetPathState(CharactersMovingTowards > 0);
       }
     }



Character

A basic character that will move towards a PathPoint

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;

     public class Character : MonoBehaviour
     {
       /// <summary>
       /// The Path Point that is on the same gameobject of this character (if avaliable)
       /// </summary>
       public PathPoint MyPathPoint { get; private set; }
       public float movementSpeed = 4.0f;

       private PathPoint targetPathPoint;
       private Transform tran;
       private Vector3? target;
       private bool movementState;
       private bool continuousMode;



       private void Awake()
       {
         tran = transform;
         MyPathPoint = GetComponent<PathPoint>();
       }

       private void Update()
       {
         if (movementState && target.HasValue)
         {
           tran.position = Vector3.MoveTowards(tran.position, target.Value, movementSpeed * Time.smoothDeltaTime);

           if (!continuousMode && tran.position == target.Value)
           {
             ClearTarget();
           }
         }
       }

       /// <summary>
       /// Sets the target for this character to move towards
       /// </summary>
       /// <param name="nTarget">The new target position</param>
       /// <param name="startMoving">The new movement state to use</param>
       public void SetTarget(PathPoint nPathPoint, bool startMoving = true, bool continuous = false)
       {
         if (nPathPoint != null)
         {
           if (targetPathPoint != null)
           {
             targetPathPoint.CharacterOnPath(false);
           }

           targetPathPoint = nPathPoint;
           target = targetPathPoint.Position;
           movementState = startMoving;
           targetPathPoint.SetPathState(true);
           continuousMode = continuous;
         }
       }

       /// <summary>
       /// Removes the target position from this character.
       /// </summary>
       public void ClearTarget()
       {
         movementState = false;
         target = null;
         if (targetPathPoint != null)
           targetPathPoint.CharacterOnPath(false);
         targetPathPoint = null;
       }

       /// <summary>
       /// Alters this characters movement state
       /// </summary>
       /// <param name="moveState">The new state</param>
       public void SetMoveToTargetState(bool moveState)
       {
         movementState = moveState;
       }

       /// <summary>
       /// Alters the continuous mode of this cahacter
       /// </summary>
       /// <param name="newMode">The new mode</param>
       public void SetContinuousMode(bool newMode)
       {
         continuousMode = newMode;
       }

       public void Deselect()
       {
         // Some animation stuff
         tran.localScale = Vector3.one * 3;
       }

       public void Select()
       {
         // Some animation stuff
         tran.localScale = Vector3.one * 4.5f;
       }

       /// <summary>
       /// Makign sure the path point is updated if this character is destroyed whilst on a path
       /// </summary>
       private void OnDestroy()
       {
         if (targetPathPoint != null)
         {
           targetPathPoint.CharacterOnPath(false);
         }
       }
     }
Comment
Add comment · Show 3 · 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 sakibmd6222 · May 23, 2018 at 10:43 PM 0
Share

I tried the above codes you provided but not working at all. I wanted to move a 2D gameobject to an object that I click with mouse. It looks like the gameobject (player) is occupying the location object (I click this location object with mouse and the player moves to occupy the position of the location object). Only gameobject (player) can move, not the other three objects also known pathpoint. In one word, player will move towards the location object and occupy the position of location object if I click the location object with mouse. Location objects do not move. Only player (gameobject) can move.

Thank you..!

avatar image Tobychappell sakibmd6222 · May 24, 2018 at 01:08 AM 0
Share

Ohhhhhh its a 2D game! I'll amend the code...


The CharacterPointer class will need to be doing a Physics2D.RayCast.... not a 3D physics raycast.

avatar image Tobychappell · May 25, 2018 at 06:46 PM 0
Share

Did the updated code work for you?

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

90 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

Related Questions

I am trying to allow the player to pick up and move objects in a FPS style game 0 Answers

How to move a cube to another cube 2 Answers

Sigh... Need help with moving object a distance over time 1 Answer

Make Object Move to another Object 1 Answer

how can i make a object look at the mouse click only in the y axis? 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