Hi folks. I have converted the helpful JS click to move script (http://www.unifycommunity.com/wiki/index.php?title=Click_To_Move) to C# for my project.
There are 2 problems: 1) I don’t entirely understand how it works; 2) It is not working as advertised. Let’s tackle Problem #2 first! I’ll paste in the code I have on my Player.cs script so far:
public class Player : MonoBehaviour {
public float PlayerMoveSpeed;
private Vector3 TargetPosition;
private Transform PlayerTransform;
void Start ()
{
PlayerTransform = transform;
}
void Update ()
{
//Amount to move, move speed
float amtToMove = PlayerMoveSpeed * Time.deltaTime;
//Move the Player after they have clicked the Left Mouse Button on a location
if (Input.GetMouseButtonDown(0))
{
Plane playerPlane = new Plane(Vector3.up, PlayerTransform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast(ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
TargetPosition = ray.GetPoint(hitdist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
PlayerTransform.rotation = targetRotation;
}
}
PlayerTransform.position = Vector3.Lerp(PlayerTransform.position, TargetPosition, amtToMove);
}
}
This script is attached to my capsule game object. When I run the program, the capsule slides up on the Y-axis to about the center of the screen, then stops. I don’t know why the hitdist is set to 0.0f but I suspect that is the problem. But I just don’t know what to do with this value as it’s passed into the ray.GetPoint function.
Well, most of the script is rather advanced for me. My intention is to have the capsule smoothly move to where I click with the mouse. I do not care about things like collision or terrain at the moment (it’s a space game). It’s really important I get this basic mechanic working 100% before I continue.
Any help would be much appreciated!
Mac
Thanks syclamoth. Your suggestion fixed the issue of my object moving to the origin point. I forgot to mention that the "Input.GetMouseButtonDown(0)" doesn't result in the object moving to where I click with the left-mouse button. I moved the line: PlayerTransform.position = Vector3.Lerp(PlayerTransform.position, TargetPosition, amtToMove); into one of the IF statements but that didn't work either.
– anon29025731I also have the same problem. The object rotates in the right direction but doesn't move.
– gatorade4