Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Move until collide?

Discussion in 'Scripting' started by Ben555, Sep 24, 2020.

  1. Ben555

    Ben555

    Joined:
    May 22, 2019
    Posts:
    13


    I want it so that when I press Right Arrow Key on the red tile, it moves until it hits the green tile. All of the coloured tiles have box colliders on them with the tag of "Collide"
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Your question is really vague. This screenshot doesn't give a lot of context to how your scene is organized. For example, is there an underlying data model representing this grid? Do these tiles have scripts attached? Is the movement supposed to be instantaneous? Should it be smooth? Is it supposed to go one square at a time? Is the red tile supposed to stop BEFORE the green tile or ON it?
     
  3. Ben555

    Ben555

    Joined:
    May 22, 2019
    Posts:
    13
    @PraetorBlue

    Yeah fair enough I should have said more detail. Basically, the colour tiles are above the white ones, and I have just started the game so no code right now. I want the red tile to slide smoothly until it hits another collider. The collider is basically a square that encompasses all of the colour tile.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    If you make the colored tile colliders extend above the board, you can use a CharacterController on the red tile: https://docs.unity3d.com/Manual/class-CharacterController.html

    CharacterController has built-in collision detection without relying on Rigidbody physics. Just make sure the radius is equal to half your square length. Then you can simply do something like this:

    Code (CSharp):
    1. public CharacterController cc;
    2. public float MovementSpeed = 1f;
    3.  
    4. void Update() {
    5.   if (Input.GetKeyDown(KeyCode.RightArrow)) {
    6.     cc.Move(Vector3.right * Time.deltaTime * MovementSpeed);
    7.   }
    8. }
    Unfortunately CharacterController can only use a Capsule shaped collider for the character. So if you need to have a box shaped collider, you'll have to back up and do your own raycasting for collision detection. Not sure if you need that depending on how your game actually works.