I need help badly and i don’t know where i’m going wrong, i’m trying to move a ball on the Y axis only when i click and drag the mouse. When i click, it’s not following the ball, and when i go too far, the ball just goes crazy and i can’t figure out why its doing this. This is the part of the code that i need help with.
if (Input.GetMouseButton(0)){
float TouchPosY = (float) ((Input.mousePosition.y/1000)* 10);
Vector3 TouchPos = new Vector3 (0.0f, TouchPosY, 0.0f);
if(Input.mousePosition.y/185 - 1.1 > 0){
// This is the line where it goes up
transform.position = Vector3.MoveTowards(transform.position, TouchPos, 10 * Time.deltaTime);
} else if (Input.mousePosition.y/185 - 1.1 < 0) {
// This is the line where it goes down
transform.position = Vector3.MoveTowards(transform.position, TouchPos, -10 * Time.deltaTime);
}
First don’t directly use the position of the mouse on the screen to determine the position of an object in the world, Screen Space != World Space.
Second, if your target is below your current position then you still want to go towards your target. To go towards a target use a positive value for the third variable of Vector3.MoveTowards. It doesn’t matter if you are going up or down but if you are going towards or away to the target.
If you are using an orthographic camera then you can convert screen coordinates to world coordinates with Camera.ScreenToWorldPoint. For instance
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour{
void Update () {
if (Input.GetMouseButton(0))
{
float TouchPosY = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
Vector3 target = new Vector3(0.0f, TouchPosY, 0.0f);
transform.position = Vector3.MoveTowards(transform.position, target, 10 * Time.deltaTime);
}
}
}
If you are using a perspective camera then you need more details on how you want to calculate the target y value. For instance, you could use Camera.ScreenPointToRay to get the ray coming out of the mouse and calculate the point on the line x=0 closest this ray then use the position of this point as the target position.