Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Box collider with script : does not work

Discussion in 'Scripting' started by nicolas78, Nov 28, 2012.

  1. nicolas78

    nicolas78

    Joined:
    Sep 18, 2012
    Posts:
    7
    Hello
    I have a problem with a box collider and I cant not find from where it comes from. I have searched in the forum but I am unable to find an answer.

    I have created a scene with 3 cubes. They look like a tennis court.
    The biggest one is like the "ground", the second one is like the "net" and the last one is like the "ball". (size similar with reality for all of them)
    I have applied a box collider to all of them with the inTrigger tag unchecked.
    For the "ball" cube, I have applied gravity and a script in c#.

    When I run the scene, the "ball" cube is falling on the "ground cube" and doesn't pass through it which is normal.

    But when I move the "ball" cube, it does not stop on the "net" cube but pass through it and I don't understand why, because it should rebound or stop on it

    The code attached to the ball cube is the following one



    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class cubeposition : MonoBehaviour
    6. {
    7.  
    8.     private float Zpos = 0; //position of cube
    9.     private float a = 0; //accelaration m/s2
    10.     private float s = 0; //speed m/s
    11.  
    12.     void Update()
    13.     {
    14.         Control();
    15.         Calculation();
    16.         Vector3 pos = transform.position;
    17.  
    18.         pos.z = Zpos;
    19.  
    20.         transform.position = pos;
    21.         print(s);
    22.     }
    23.  
    24.     private void Calculation()
    25.     {
    26.  
    27.         s = a * Time.deltaTime + s;
    28.         Zpos = s * Time.deltaTime + Zpos;
    29.  
    30.     }
    31.  
    32.     private void Control()
    33.     {
    34.         if (Input.GetKey(KeyCode.Q))
    35.         {
    36.             a = 10;
    37.         }
    38.         else if (Input.GetKey(KeyCode.A))
    39.         {
    40.             a = -10;
    41.         }
    42.         else
    43.         {
    44.             a = 0;
    45.         }
    46.  
    47.  
    48.     }
    49.  
    50. }
    51.  
    Thanks for any help
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Setting a transform position directly bypasses collision. Either use forces instead or use Rigidbody.MovePosition.

    --Eric
     
  3. nicolas78

    nicolas78

    Joined:
    Sep 18, 2012
    Posts:
    7
    Thanks a lot Erich for your answer.
    I completely missed that.
    Regards