- Home /
2D Point & Click Movement not moving
I'm trying to make my character move to virtually any spot in an area that I click on. I'm currently using code and assets from the 2D Roguelike tutorial. I have Floor tile prefabs all containing a 2DBoxCollider set as Trigger.
I have also been given code that is supposed to check for the mouse's position, draws a raycast and starts moving the character to that position with lerping. MouseMovement script(attached to MainCamera) public class MouseMovement : MonoBehaviour { public GameObject Movechild = null; LerpToPoint Test = null;
// Use this for initialization
void Start ()
{
if(Movechild)
{
Test = Movechild.GetComponent<LerpToPoint>();
}
}
// Update is called once per frame
void Update ()
{
if (Input.GetButtonUp("LMB"))
{
//var vMoveLocation = Input.mousePosition;
var vMoveLocation = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Ray ray = Camera.main.ScreenPointToRay(vMoveLocation);
RaycastHit hit = new RaycastHit();
//ray = Camera.main.ScreenPointToRay(Input.mousePosition);
print("Mouse: " + vMoveLocation);
//if (Physics.Raycast(ray, out hit))
//if (Physics.Raycast(vMoveLocation, out hit, Vector3.forward, 100))
//if (Physics.Raycast(vMoveLocation, out hit, Vector3.forward, 100))
//if (Physics.Raycast(vMoveLocation, Vector3.forward, out hit))
if (Physics.Raycast(ray, out hit))
{
//Debug.Log(hit.collider.name);
print("Clicked");
GameObject.Instantiate(Resources.Load("testSprite"), hit.point, Quaternion.identity);
Test.EndPos = hit.point;
Test.Activate();
}
else
{
print("Point: " + hit.point);
}
}
}
}
LerpToPoint(attached to Player), which moves the character to the area clicked.
public class LerpToPoint : MonoBehaviour
{
public Vector3 EndPos = new Vector3(0,0,0);
Vector3 StartPos = new Vector3(0, 0, 0);
bool Active = false;
private float startTime;
public float Duration = 0.05f;
void Start()
{
StartPos = transform.position;
}
public void Activate()
{
Active = true;
startTime = Time.time;
StartPos = transform.position;
}
// Update is called once per frame
void Update ()
{
if(Active == true)
{
float distTravelled = (Time.time - startTime) / Duration;
float fracJourney = Time.time - startTime;
transform.position = Vector3.Lerp(StartPos, EndPos, distTravelled);
if(fracJourney >= Duration)
{
Active = false;
}
}
}
}
I've tried different combinations of code for Raycasting, but I can't seem to get it to move no matter what I do. What is a good way to go about this?
Answer by UnityTrouble · Dec 27, 2016 at 10:39 PM
Hi, we made a 2d/2.5d point and click and it is now available on the asset store at https://www.assetstore.unity3d.com/en/#!/content/76020
It might help you with your game. We also take requests of code so let us know what you need and we might be able to add it to the asset store.