Reputation: 93
I have a question. I have to make the character move in two positions, just like in the picture below.
All I want to know is how to do this thing. For example, character moves automatically to the right, then when it clicks up, it already moves to the top bar and still moves to the right, and already when it clicks down it to go back to the bar down.
public float speed;
public GameObject[] buttons;
private void Start()
{
foreach (GameObject button in buttons)
button.GetOrAddComponent<MouseEventSystem>().MouseEvent += ChangeBoyPosition;
}
private void ChangeBoyPosition(GameObject target, MouseEventType type)
{
if (type == MouseEventType.CLICK)
{
int buttonIndex = System.Array.IndexOf(buttons, target);
if (buttonIndex == 0)
{
//do down position
}
else
{
//do up position
}
}
}
void Update()
{
//used for automatic movement
//set a speed that responds to the speed of the boy
//automatically move it to the right, then we will change the direction when it reaches the X axis limit
transform.Translate(Vector3.right * speed * Time.deltaTime);
}
Basically I have two buttons, up and down, with these I manipulate the character. If anyone knows how I could make this physics simpler? Thank you!!!
Upvotes: 0
Views: 49
Reputation: 416
You can try using Physics2D.gravity
to modify the y value.
Physics2D.gravity = new Vector2(0, -1); // To go down
Physics2D.gravity = new Vector2(0, 1); // To go up
You'd probably be putting this in an update function since it needs to check inputs, so I would recommend creating two vectors gravityUp
and gravityDown
and setting Physics.gravity
equal to one or the other, depending on which direction you want to go.
Like this:
Vector2 gravityUp = Vector2.up;
Vector2 gravityDown = Vector2.down;
The same would apply in 3D, except you'll have to use Vector3
and Physics.gravity
.
Your code would possibly look like this:
Vector2 gravityUp = Vector2.up;
Vector2 gravityDown = Vector2.down;
private void ChangeBoyPosition(GameObject target, MouseEventType type)
{
if (type == MouseEventType.CLICK)
{
int buttonIndex = System.Array.IndexOf(buttons, target);
if (buttonIndex == 0)
{
Physics2D.gravity = gravityDown;
}
else
{
Physics2D.gravity = gravityUp;
}
}
}
Upvotes: 1