Reputation: 93
I have a little dilemma. I'm develop a game and I need to do something that I do not understand. I have an object that moves up and down with this script:
void FixedUpdate()
{
if (canClick)
{
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(0f, moveVertical, 0f);
Tucan.GetComponent<Rigidbody2D>().velocity = movement * speed;
Tucan.GetComponent<Rigidbody2D>().position = new Vector3
(
-7.5f,
Mathf.Clamp(Tucan.GetComponent<Rigidbody2D>().position.y, boundary.yMin, boundary.yMax),
0.0f
);
}
}
Now I want to do that when I click Mouse (0), the object moves upwards if Mouse.y> 0 and respectively down if Mouse.y position <0
private void Update()
{
Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetMouseButton(0))
{
if (mouse.y > 0f)
{
}
else
{
}
}
}
How to do the same code as FixedUpdate, run it in Update, but do the checks. And already moving in dependence on Mouse.y.
Upvotes: 0
Views: 54
Reputation: 3108
Just compare the WorldSpace mouse positions Y to your GameObjects Y
void Update()
{
Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetMouseButton(0))
{
Vector3 movement;
if (mouse.y > Tucan.transform.position.y)
{
movement = Vector3.up;
}
else
{
movement = Vector3.down;
}
Tucan.GetComponent<Rigidbody2D>().velocity = movement * speed;
}
}
EDIT
Since you wanted a split screen solution
so the screen separates it in two, and when I click up, it moves up and vice versa
void Update()
{
var mouse = Input.mousePosition;
mouse.y -= Screen.height / 2;
if (Input.GetMouseButton(0))
{
Vector3 movement;
if (mouse.y > 0)
{
movement = Vector3.up;
}
else
{
movement = Vector3.down;
}
Tucan.GetComponent<Rigidbody2D>().velocity = movement * speed;
}
}
Upvotes: 1