- Home /
Move towards mouse position on button down (2D)?
Hey everyone, so I have an astronaut character (in zero gravity) in 2d, and I'm just trying to get it to move towards the mouse position when I'm holding down the left mouse key. Right now if I click and hold on the right side of the screen the astronaut moves towards the mouse pos, but if I click and hold on the left side of the screen the character moves away from the mouse, so I'm kind of confused. My script is simple enough so if anyone can see the problem or can offer any improvements, I'd appreciate it. Also, the astronaut is a ragdoll, so that's why the force is being applied to a child of the astronaut (the main body of the ragdoll).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
Rigidbody2D rigid2D;
public float speed;
public float acceleration;
public float deceleration;
public float maxSpeed;
void Start ()
{
rigid2D = transform.GetChild(1).GetComponent<Rigidbody2D>();
}
void Update ()
{
if (Input.GetMouseButton(0))
{
if (speed <= maxSpeed)
{
speed = speed + acceleration * Time.deltaTime;
}
else
{
speed = maxSpeed;
}
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rigid2D.AddForce(mousePos * speed);
}
else
{
if (speed > 0)
{
speed = speed - deceleration * Time.deltaTime;
}
else
{
speed = 0;
}
}
}
}
Answer by Tsaras · Apr 14, 2019 at 07:01 AM
Right now the way you are calculating the force to apply does not represent any direction. To get a direction you can subtract 2 positions, for example something like mousePos - transform.position
. However, mousePos is a 2D vector therefore you will need to properly convert it to correspond to the plane your astronaut moves in. If it is the XY plane you can just use it as is, otherwise you need to use Vector3 mousePos3 = new Vector3(mousePos.x, 0, mousePos.y)
for the XZ plane.
So you can try something like this:
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position; //if astronaut is in XY plane
rigid2D.AddForce(direction.normalized * speed); //normalize direction to make the movement speed independent from distance and only controlled by the speed variable
The character still appears to be moving away from the mouse at times, I guess I'll have to look into it more. Thanks for the answer though, the whole direction aspect makes sense now.
Your answer
Follow this Question
Related Questions
How to make object fallow the mouse ?? 1 Answer
Top down movement and rotation 2 Answers
Moving Objects using the mouse only 0 Answers
2d Spaceship smooth mouse movement 0 Answers
Call an exorcist. 1 Answer