- Home /
Move Object by dragging (mobile) makes the balls fall from the cup
I have this cup that contains balls inside. All 2D I am using Rigidbody2d and Collider2d.
When running in unity and moving the cup (with arrow keys) the balls stay inside the cup. I also added drag movement for Android touch to move the cup.
The problem is that when moving the cup too fast (by draging) the balls fall from the cup collider (using Polygon colider 2d).
Code for movement is:
public float speed = 0.1F;
void Update() {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
transform.Translate(-touchDeltaPosition.x * speed, -touchDeltaPosition.y * speed, 0);
}
}
I tried to play with the speed parameter but it wont really help. if the cup movement is too slow it is not very useful for me. I believe it is related the velocity/force of the ball or cup which makes the cup collider miss...
Edit: I tried to increase the size of the colliders using 2d box colliders instead of Polygon 2d collider and still it doesn't work.
Any help on this would be appreciated greatly...
I would also try using Rigidbody2D.$$anonymous$$ovePosition rather than Translate.
I tried the following: private var speed : Vector3 = Vector3 (3, 0, 0); function FixedUpdate () { if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.$$anonymous$$oved) { rigidbody.$$anonymous$$ovePosition(rigidbody.position + speed * Time.deltaTime); } }
But the rigidbody2d does move at all on touch..
Shouldn't you be using rigidbody2D ins$$anonymous$$d of rigidbody? I thought there would be a warning about no rigidbody being attached but there isn't. It was added just in version 4.5 so you might need to update to use it.
I did try with rigidbody2D but the cup did not move with touch.. my mistake when copy/pasting here.
Answer by ABerlemont · Jun 24, 2014 at 08:58 AM
I worked on a similar project. Never managed to get that to work ... Even with slow physic/rigidbody/MovePosition2D()
Best option for now is to move the cup by using physic forces, not MovePosition()/transform.position
// Apply a force that attempts to reach our target velocity
Vector3 velocityChange = ...;
controller.AddForce(velocityChange, ForceMode.VelocityChange);
Hoped 4.5 would change something but it didn't.
Do i add this to the fixedupdate() inside if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.$$anonymous$$oved)?
I think that you need to get the difference between the origin position and destination (based on touch behavior) and apply that diff to velocity.
Thank you for the reply. Can you provide an example for this?