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

Random Position (Based On Screen Size)

Discussion in 'Scripting' started by GoodNight9, May 8, 2021.

  1. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    Hello!! I have a simple game where you try and tap a target. When you succeed the target will randomly pick a new position on the screen and move their > and the process repeats. My problem is I don't know how to code it to where it never appears outside the bounds of the parent RectTransform area.

    Is there even a way to do this?? Here's what I have so far: But it doesn't account for any changes in screen size. So while -160/160x, and -270/270y are the maximum positions of the a phone size, if I move to an ipad screen size it only picks position within a small part of the screen :(

    https://ibb.co/XCnQ5tP
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class ButtonControls : MonoBehaviour
    7. {
    8.     public RectTransform myRect;
    9.  
    10.     public void WasClicked()
    11.     {
    12.         myRect.transform.localPosition = new Vector3(Random.Range(-160,160), Random.Range(-270,270), 0);
    13.     }
    14. }
    Thank you for your time!
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    GoodNight9 likes this.
  3. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123