Hi
I want my player to move A to B, B to C by touching right arrow and C to B, B to A by touching left arrow as shown in attached image. Because my player wants to catch balls come from “*” position marked as attachment. I used two difference method for implement player movement. But It doesn’t stop at A,B or C position all time. Some time it goes far or less. Event Trigger is used to arrow touch detection.
My target is for android device and I use unity 5.4 and c# to develop my game. It’s 2D game.
The Code I used is put below. I have commented the second method I used.
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float leftBoundry, rightBoundry;
}
public class MovePlayer : MonoBehaviour
{
public Boundary boundary;
public float speed;
Rigidbody2D playerRigBody;
Vector2 movement;
float input = 0;
void Start()
{
playerRigBody = this.GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
PlayerMovement(input);
}
void PlayerMovement(float horisontalInput)
{
//movement.x = playerRigBody.velocity.x;
//playerRigBody.velocity = movement;
//movement = playerRigBody.velocity;
//movement.x = horisontalInput * speed * Time.fixedDeltaTime;
//playerRigBody.velocity = movement;
movement = playerRigBody.position;
movement.x = movement.x + (0.4f * horisontalInput);
playerRigBody.position = movement;
playerRigBody.position = new Vector2
(
Mathf.Clamp(playerRigBody.position.x, boundary.leftBoundry, boundary.rightBoundry),
-3.77f
);
}
public void UserInput(float horisontalInput)
{
//prevent player move beyond the boundy after met boundry
//if ((horisontalInput == 1 && playerRigBody.position.x >= boundary.rightBoundry) || (horisontalInput == -1 && playerRigBody.position.x <= boundary.leftBoundry))
//{
// input = 0;
//}
//else {
// input = horisontalInput;
//}
input = horisontalInput;
}
}