Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by paulaceccon · Jan 02, 2015 at 12:22 PM · movementspriteoverlap

Sprites that moves overlapping

Hi, I'm currently working on a project in which some NPCs are spawned in the scene. These NPCs are represented by Sprites and they move 'walk in a street', moving from one point to another. Their start and end positions are generated randomly:

 using UnityEngine;
 using System.Collections;
 
 public class ClientSpawner : MonoBehaviour
 {
     [SerializeField]
     private float _spawnTime; 
 
     [SerializeField]
     private GameObject[] _clientCharacter;
 
     [SerializeField]
     private int _clientCount;
 
     [SerializeField]
     private Transform _gameArea;
 
     [SerializeField]
     private float _padding;
 
     private int _clientsSpawned = 0;
 
     private Vector4 _bounds;
     
     private void Start()
     {
         Vector3 min = Camera.main.ScreenToWorldPoint( UICamera.mainCamera.WorldToScreenPoint( _gameArea.collider.bounds.min ) );
         Vector3 max = Camera.main.ScreenToWorldPoint( UICamera.mainCamera.WorldToScreenPoint( _gameArea.collider.bounds.max ) );
 
         _bounds = new Vector4( min.x + _padding,
                                max.x - _padding,
                                min.z + _padding,
                                max.z - _padding );
 
         if ( _clientCount > 0 )
             InvokeRepeating ("Spawn", 0, _spawnTime);
     }
 
     private Vector3 SortPosition( bool atRight )
     {
         Vector3 position;
         if ( atRight )
             position =  new Vector3( _bounds[0], 0f, Random.Range( _bounds[2], _bounds[3] ) );
         else 
             position =  new Vector3( _bounds[1], 0f, Random.Range( _bounds[2], _bounds[3] ) );
 
         return position;
     }
 
     private void Spawn()
     {
         _clientsSpawned ++;
 
         if(_clientsSpawned == _clientCount)
             CancelInvoke( "Spawn" );
 
         bool atRight = ( Random.Range(0, 2) == 1 );
 
         Vector3 startPosition = SortPosition( atRight );
         Vector3 finalPosition = SortPosition( !atRight );
          
         GameObject client = GameObject.Instantiate( _clientCharacter[Random.Range( 0, _clientCharacter.Length )], 
                                                    startPosition, Quaternion.identity ) as GameObject;
 
         if (!atRight)
         {
             Flip( client.GetComponentInChildren<Transform>() );
         }
 
         client.GetComponent<ClientBehavior>().EndPosition = finalPosition;
         client.SetActive( true );
         client.transform.parent = transform;
     }
 
     private void Flip( Transform t )
     {
         Vector3 scale = t.localScale;
         scale.x *= -1;
         t.localScale = scale;
     }
 }

When they are walking, they may pass through a common position. In this case, however, I have no control of which NPC will be in front of the other, getting some incorrect cases:

alt text alt text

How could I correctly treat this? My NPCs have a script in which they only know what should be their final positions:

 public class ClientBehavior : MonoBehaviour
 {
     private Animator _animator;
 
     private int _state; /** 0 (idle), 1 (walking) or 2 (restless) **/
 
     [SerializeField]
     private float _velocity;
 
     private Vector3 _endPosition = Vector3.zero;
     public Vector3 EndPosition
     { 
         get { return _endPosition; }
         set { _endPosition = value; }
     }
 
     private void Awake()
     {
         _controller = GetComponent<CharacterController>();
         _animator = GetComponentInChildren<Animator>();
 
         _state = 1;
         _animator.SetInteger("State", _state);
     }
     
     private void FixedUpdate()
     {
         if ( _state == 1 )
             Walk();
     }
 
     private void Walk()
     {
         transform.position = Vector3.MoveTowards(transform.position, _endPosition, _velocity * Time.fixedDeltaTime);
 
 //        Vector3 dir = ( _endPosition - transform.position ).normalized;
 //        dir *= _velocity * Time.fixedDeltaTime;
 //        _controller.SimpleMove( dir );
     }
 }
 

Thank you.

captura de tela 2015-01-02 às 10.03.07.png (51.4 kB)
captura de tela 2015-01-02 às 10.02.56.png (99.9 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Pitomator · Jan 02, 2015 at 04:56 PM

Hi Paulaceccon,

I not 100% sure if I understood your question correctly, but I am assuming that you are having issues with the random drawing order?

A solution to this issue, I used in in past projects, is to set the "Sorting Order" on the SpriteRenderer acording to your characters currenty Y position. So if the character is further up (in the back) it draws them behind the characters that are further down (in front).

Here is a code snapped that does this:

 SpriteRenderer sr = gameObject.GetComponent<SpriteRenderer>();
     Void Update(){        
         sr.sortingOrder = (int) (-transform.position.y);
         //you may need to multiply this value if an int does not give you enough resolution.
     }






Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image paulaceccon · Jan 03, 2015 at 02:56 PM 0
Share

Thank you, @$$anonymous$$omator. (:

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

27 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Megaman in Unity! Help with movement. 0 Answers

Upon mouseclick, move sprite few pixels to right 1 Answer

Animator warning in editor, animation is preventing script from working 1 Answer

Drag a sprite around with mouse, but have it not overlap other sprites 0 Answers

Why is my quad not moving in sync with its collider? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges