0

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.

2
  • Do you mean if the mouse is above the object? of i mouse is above center of screen? Commented Jul 12, 2018 at 8:23
  • so the screen separates it in two, and when I click up, it moves up and vice versa Commented Jul 12, 2018 at 8:39

1 Answer 1

1

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; } } 
Sign up to request clarification or add additional context in comments.

8 Comments

It does work, i reproduces it myself first before posting
But i will make an edit to make it a split screen thing instead!
I do not know why, but it really does not move the object
I changed and speed was higher, nothing at all
Dont know what boundary values are, so i removed those ifs and put 255 instead of maxSpeed and my object moves
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.