1
\$\begingroup\$

As we know, Transform.Translate() ignores collisions. What functionality do I need to add to my code so that when my collider hits something, the physics system makes it stop?

Here is what I'm doing now:

void FixedUpdate()
{
    foreach (Touch touch in Input.touches)
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition; 
            Vector2 pos = touchDeltaPosition;
            pos.x = touchDeltaPosition.x * speed;
            pos.y = touchDeltaPosition.y * speed;
            transform.Translate(pos.x,pos.y,0);

            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1000))
            {
                if (hit.collider.tag=="Environment")
                {
                    Cubecall();
                }
            }
        }
    }
}
void Cubecall()
{
    anim.enabled = true;
}
\$\endgroup\$

bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

  • \$\begingroup\$ Have you considered not moving your object using Transform.Translate, but using physics methods like velocity/force instead? \$\endgroup\$ – DMGregory Apr 20 at 13:31
  • \$\begingroup\$ In fact, it looks like you've asked multiple versions of this question in the past day. Can you please clarify the difference in what you're asking here, here, and here? If this is all about solving one problem, then I'd recommend deleting the copies and edit the one remaining question to contain the details you want to share. Spamming the site with near-duplicates makes it harder to find good answers, and can result in account restriciton \$\endgroup\$ – DMGregory Apr 20 at 13:45
  • \$\begingroup\$ actually what i am trying to do when my cube touch another collider(cube or object) then stop my cube, as my previous post you should be remove, i am many website refer but not proper solution, i m trying to do last three days, you can give any idea for this \$\endgroup\$ – Rahul Patil Apr 20 at 15:09
0
\$\begingroup\$

The very easiest and most consistent way is to keep the object in control of the physics system at all times. That way, it can handle the collisions and physics responses internally.

Your code could then look something like this:

Rigidbody body;

void Start() {
    body = GetComponent<Rigidbody>();
}

void FixedUpdate() {
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        var touch = Input.GetTouch(0);
        var touchVelocity = touch.deltaPosition/touch.deltaTime; 
        var targetVelocity = touchVelocity * speedMultiplier;

        body.velocity = targetVelocity;
    }
}

I've removed the foreach because you weren't actually using the results of the additional touches - touch 0 was the only one your code ever read, it just applied touch 0 repeatedly if there were other touches present.

I also simplified the multiplication by speed (you don't need to do it one component at a time) and renamed the varaible to speedMultiplier to convey that it's a magnification/minification factor on the speed of the touch itself. I adjusted the touch deltaPosition by its deltaTime so that you get consistent results independent of the relative timing/sampling frequency of touch updates and FixedUpdate.


Or, if you want to move using transform.Translate then you should "look before you leap": do your physics query first to check how far you can move, and then move only that far.

Vector3 direction = targetVelocity.normalized;
float maxTravelThisFrame = targetVelocity.magnitude * Time.deltaTime;

RaycastHit hit;
if ( Physics.BoxCast(
         transform.position,  // Where our cube is now.
         halfExtents,         // How big is our cube, measured from the center out?
         direction,          // Which direction do we want the cube to go?
         out hit,             // Capture information about what we hit.
         transform.rotation,  // How is our cube oriented?
         maxTravelThisFrame   // Where to stop our query?
)) {
    // Moving a hair less than we're allowed leaves us some padding,
    // helping to avoid kissing contacts & unintended tunneling.
    maxTravelThisFrame = Mathf.Max(0, hit.distance - 0.001f);
}

transform.Translate(maxTravelThisFrame * direction, Space.World);

Lastly, I've noticed in your previous versions of this question, you were using a mix of 2D and 3D physics types. These are processed by completely separate physics engines in Unity, so a 3D Rigidbody or BoxCast will not respond to collisions with a BoxCollider2D. Be sure you're using one regime - 2D or 3D - consistently, with all physics components and callback methods you want to interact together.

\$\endgroup\$
  • \$\begingroup\$ i am using the BoxCollider2d on my obstacles and my cube will be sprite2D,is possible to when sprite2D(cube) touch Boxcollider2d, it is collided or not?? \$\endgroup\$ – Rahul Patil Apr 22 at 4:54
  • \$\begingroup\$ You should use the 2D colliders on both and a Rigidbody2D on your character sprite, or use the Physics2D version of BoxCast rather than the 3D version above. \$\endgroup\$ – DMGregory Apr 22 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.