- Home /
how to change direction of the moving object?
Hey guys, im working on a game. I have and object (ball) rolling on a platform forwardly with its own speed and through the rings. All i want is when i click on right side of screen, move the ball to the right and same for left side. I did something closely but its not smooth and i guess im doing things wrong.
My code is
public class PlayerController : MonoBehaviour {
Vector3 targetPosition;
public float speed = 2f;
void Update ()
{
transform.Translate(0, 0, speed * Time.deltaTime);
if(Input.GetMouseButtonDown(0))
{
SetTargetPosition();
}
}
void SetTargetPosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
targetPosition = hit.point;
transform.LookAt(targetPosition);
}
}
Screenshot of project: [1]: /storage/temp/129974-afds.png
Answer by ignacevau · Dec 25, 2018 at 10:25 AM
You could simply check whether the user clicked the left half or the right half of the screen, and then move the player to the left or the right instead of using the transform.LookAt() method.
private Vector3 HorizontalMovement;
private void Update()
{
if(Input.GetKey(KeyCode.Mouse0))
{
// Clicked on the right half
if(Input.mousePosition.x > (Screen.width / 2))
{
HorizontalMovement = Vector3.right;
}
// Clicked on the left half
else
{
HorizontalMovement = Vector3.left;
}
}
else
{
HorizontalMovement = Vector3.zero;
}
}
You can later use this HorizontalMovement vector to move your player on the horizontal axis:
[SerializeField] float SpeedForward;
[SerializeField] float SpeedSideways;
private void FixedUpdate()
{
Vector3 forwardVector = Vector3.forward * SpeedForward;
Vector3 horizontalVector = HorizontalMovement * SpeedSideways;
rb.AddForce(forwardVector + horizontalVector);
}
You don't have to use Rigidbody.AddForce(), this was just a quick solution ('rb' is the Rigidbody component)