Hello everyone. I’m working on script in which when the player clicks somewhere on screen the player will move in that direction. When I tested the script, the character moves where I click but I found the following problems
I want the character to keep moving to that position even when the mousebutton is released
There are times where the character disappears if I click on the player.
Here’s the player movement script.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public Plane Player_Plane;
public float speed;
public float Player_Distance=0.0f;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Ray Player_Direction = Camera.main.ScreenPointToRay(Input.mousePosition);
Player_Plane.Raycast(Player_Direction,out Player_Distance);
transform.position= Vector3.MoveTowards(transform.position,Player_Direction.GetPoint(Player_Distance),speed);
}
}
}
I’ve not worked too much with raycasts but I think I know your problem. Your code is stuck in a conditional that only executing when the mousebutton is down.
I’m going to guess this works like a Lerp function?
But I don’t know. But I don’t have to know that to know there is a problem. Your code only executes when the mouse is down. Something, likely the line I copy-pasted, has to be outside this conditional otherwise nothing technically happens when the mouse is not held down. Unless Vector3.MoveTowards starts a coroutine under the hood which I don’t think it does.
Well I got part some parts of the code working. I’m able to get the 2d character to move based on the mouse click. However, after a few mouse clicks the character disappears. Here’s the updated code (I did not comment it yet)
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
private float speed=1.0f;
private float Player_Distance;
private Ray Player_Direction;
private Vector3 Position_Checker;
void Start()
{
Position_Checker = transform.position;
}
// Update is called once per frame
void Update ()
{
if (Vector3.Distance (Position_Checker, transform.position) < .5f)
speed = 0.0f;
else
speed = 10.0f;
if (Input.GetKey (KeyCode.Mouse0))
{
Plane Player_Plane = new Plane(Vector3.up,transform.position);
Player_Direction = Camera.main.ScreenPointToRay (Input.mousePosition);
Player_Plane.Raycast (Player_Direction, out Player_Distance);
}
transform.position= Vector3.MoveTowards(transform.position,Player_Direction.GetPoint(Player_Distance),Time.deltaTime*speed);
Position_Checker = Player_Direction.GetPoint (Player_Distance);
}
}