Moving GameObject without transform.position through a touchscreen? (In Unity3d)

1.4k views Asked by At

I'm developing a mobile game in Unity3d which the player needs to move a stick that is placed just a little bit higher then the finger with transform.position and block a ball that is moved with Force.Mode2D.impulse. The problem is that the ball goes through the stick if the stick is moved too fast. Could anyone please teach me how to code the stick movement with Force (or any other way that works) that still moves according to the finger position on touch screen ( A.K.A Input.mousePosition) instead of using buttons?

The code goes as such if anyone needs the info;

Stick:

 float defencePosX = Mathf.Clamp( Input.mousePosition.x / Screen.width * 5.6f - 2.8f , -2.8f, 2.8f);
 float defencePosY = Mathf.Clamp( Input.mousePosition.y / Screen.height * 10 - 4f, -3.3f, -0.5f);
 this.transform.position = new Vector3 (defencePosX, defencePosY, 0);

Ball:

projectileSpeed = Random.Range (maxSpeed, minSpeed);
 projectileSwing = Random.Range (-0.001f, 0.001f);
 rb.AddForce (new Vector2 (projectileSwing * 1000, 0), ForceMode2D.Impulse);
 rb.AddForce (new Vector2 (0, projectileSpeed), ForceMode2D.Impulse);

a video of the bug: https://youtu.be/cr2LVBlP2O0 basicly if i dont move the stick it hits but if i move it fast the ball goes right through. (the bouncing sound effect doesnt work if itss too fast as well)

2

There are 2 answers

1
BJennings On BEST ANSWER

When working with physics objects, you'll want to use just the Rigidbody component when moving them. Otherwise, it's interpreted as a teleport and no physics is applied and no movement is calculated.

Try using Rigidbody.MovePosition instead of transform.position.

Also, make sure the Rigidbody components on your stick AND ball both have collisionDetectionMode set to 'Continuous Dynamic'. That's how you get small fast-moving physics objects to hit one another in between frames.

 float defencePosX = Mathf.Clamp( Input.mousePosition.x / Screen.width * 5.6f - 2.8f , -2.8f, 2.8f);
 float defencePosY = Mathf.Clamp( Input.mousePosition.y / Screen.height * 10 - 4f, -3.3f, -0.5f);
 rb.MovePosition(new Vector3 (defencePosX, defencePosY, 0));
5
Doh09 On

Id recommend that you set the balls force to Vector3.zero before adding force to it, or that you use the collider of your blocking movement as a bounce pad for the ball.

Please remember to check that your colliders are scaled correctly according to the blocker.

A video displaying your issue would be helpful to understand it better.