- Home /
How to make an object move to another object's location in a 2d game?
Hello, I am trying to figure out how to make a game object (like a player) move to another object (like a house or dungeon) that the player clicked on, but only if they clicked on it. Meaning the player can't move around freely. It doesn't really matter how it gets there, so path finding or anything like that doesn't matter.
I'm sorry if this is a stupid thing to ask, or too much to ask of.
Answer by Ali-hatem · May 01, 2016 at 11:25 AM
public float speed;
void Update(){
if (Input.GetMouseButton(0)){
Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);//converting
target.z = transform.position.z;
transform.position = Vector3.MoveTowards(transform.position, target, speed);
}
}
Answer by g__l · May 01, 2016 at 10:52 AM
(EDIT - Sorry this only answers the object moving towards another part, i should have read the full description and not been lazy reading the title)
Well this should be relatively simple with Vector2.MoveTowards()
then make your code look something like this
using UnityEngine;
using System.Collections;
public class MoveTowards : MonoBehaviour {
GameObject HouseOrDungeon;
GameObject Player;
float speed;
// Update is called once per frame
void Update () {
float step = speed * Time.deltaTime;
Player.transform.position = Vector2.MoveTowards(Player.transform.position, HouseOrDungeon.transform.position, step);
}
}
Check out the documentation (here)
Hope that helps but please remeber (do this before asking)
this is right but he wants
move to another object (like a house or dungeon) that the player clicked on
Thanks for letting me know, should have read the full question.
Not sure how it would work for the clicking on an object part, i guess you could get the click's x and y coordinates and compare them against the surrounding objects on the screens using (screen point to game point)
by using Vector3
to be = to touch position & ins$$anonymous$$d of HouseOrDungeon.transform.position
the target will be that Vector3
with taking care of converting click position from pixels to points because clicks & touches defined by pixels where transform defined by points for example if we have 800 pixel screen width then click in the middle will bee 400 then you will send the transform 400 points imagine that so i think now i have to answer
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Joystick problems 1 Answer
Question on Sprite and Movement 0 Answers