Issue with the direction of the swipe and the movement of the ball.

I’m developing a 3D Roll Ball game to understand ball mechanics. I want the ball’s z-direction to align with its movement, and I’ve added an animation for realistic rolling. However, I’m facing an issue: when the user swipes in a direction, the ball moves in the opposite direction. How can I fix this and improve the script?

public Animator animator;
public float swipeSpeed = 5f;
public float maxSpeed = 10f;
public float acceleration = 2f;

private Rigidbody rb;
private Vector3 swipeDirection;
private Vector3 velocity;

private void Start()
{
rb = GetComponent();
}

private void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);

if (touch.phase == TouchPhase.Began)
{
swipeDirection = Vector3.zero;
}

if (touch.phase == TouchPhase.Moved)
{
swipeDirection = new Vector3(touch.deltaPosition.x, 0, touch.deltaPosition.y).normalized;
// swipeDirection = touch.deltaPosition.normalized;
velocity += swipeDirection * acceleration * Time.deltaTime;
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
}
}
else
{
velocity = Vector3.Lerp(velocity, Vector3.zero, Time.deltaTime);
}

rb.MovePosition(rb.position + velocity * Time.deltaTime);

if (velocity != Vector3.zero)
{
transform.rotation = Quaternion.LookRotation(velocity);
}

animator.speed = velocity.magnitude / 4;

if (velocity.magnitude < 0.01f)
{
animator.enabled = false;
}
else
{
animator.enabled = true;
}
}

Anytime you have a vector and want the opposite, you can negate it by putting unary minus before the vector when you go use it, or else subtract with it instead of add with it.

Alternately, swapping the input arguments to the subtraction step can do the same thing, if you are computing the delta yourself.

Otherwise…

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

• Do not TALK about code without posting it.
• Do NOT post unformatted code.
• Do NOT retype code. Use copy/paste properly using code tags.
• Do NOT post screenshots of code.
• Do NOT post photographs of code.
• Do NOT attach entire scripts to your post.
• ONLY post the relevant code, and then refer to it in your discussion.
1 Like

As above, please use code-tags and not plain text when posting code.

Thanks.

Okay Thank you!