- Home /
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;
}
}
}
So you'd like to be able to select a gameobject, and tell it to move to another gameobject?
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);
}
}
}
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..!
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.
Your answer
Follow this Question
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