Hi,
I am an absolute beginner with Unity, however, have some basic web programming experience.
I’m working through one of the many fantastic video training tutorials and have followed through and built a basic game. At the moment, the Player sprite moves around with the arrow keys. I’m now in the process of messing around with the game that I’ve built and am having some success with the changes I’m making which is cool!
However, there’s one thing I can’t seem to find the answer to and am wondering if anybody could help?
I’d like to experiment with moving the Player with the mouse position instead of using keys. Furthermore, I’d like to have the option of choosing between movement in all direction, movement in the X axis only and movement in the Y axis only.
The project (PlaygroundProject) I’m working on has lots of wonderful assets including a script for making the Player follow the mouse cursor. However, it requires the mouse button to be clicked in order to work. Is anybody willing to take a look at the script and edit it to make this happen for me? I’m sure it’s a simple line of code somewhere, and would be really great to see what and where, as I’ve now exhausted googles many results and am not really getting anywhere!
Many thanks in advance. Here’s the code…
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class FollowCursor : MonoBehaviour
{
public float speed = 2f;
private Vector3 currentTarget; //the mouse position
private Vector3 initialPosition;
private bool targetReached = true;
private float progressToTarget = 0f;
private float distance;
private float acceleration;
private float accelerationDistance = 3f;
private Rigidbody2D rb2D;
private Vector3 newPosition;
private void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
private void Update ()
{
if(Input.GetMouseButtonDown(0))
{
currentTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition); //mouse position is taken only on left click
currentTarget.z = 0;
initialPosition = transform.position;
distance = Vector3.Distance(transform.position, currentTarget);
//reset some variables
progressToTarget = 0f;
acceleration = .1f;
targetReached = false;
}
//the movement routine
if(!targetReached)
{
if(progressToTarget <= accelerationDistance / distance)
{
//accelerate
acceleration += Time.deltaTime * 2f;
acceleration = Mathf.Min(acceleration, 1f);
}
else if(progressToTarget < 1f - accelerationDistance / distance)
{
//constant speed
acceleration = 1f;
}
else
{
//decelerate
acceleration -= Time.deltaTime * 2f;
acceleration = Mathf.Max(acceleration, .1f);
}
//calculate the progress to target
progressToTarget += Time.deltaTime * speed * acceleration / distance * 10f;
if(progressToTarget <= 1f)
{
//cache the movement
newPosition = Vector3.Lerp(initialPosition, currentTarget, progressToTarget);
}
else
{
//stop
targetReached = true;
}
}
}
private void FixedUpdate()
{
if(!targetReached)
{
rb2D.MovePosition(newPosition);
}
}
}