Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by RockmanDeividu · Oct 04, 2018 at 03:05 PM · movementmovement scriptcursor

Mouse move object according to grid

Hello people!

I'm making a 2D Turn based strategy - actually I'm recreating NINJA BURAI DENSETSU for Genesis -, and I'm cracking my head on one issue.

In the original game the cursor moves within a grid, just moving it up, down, left or right, and i did that well, as you can see below:

https://www.youtube.com/watch?v=hjk8YQlJAR4&feature=youtu.be

BUT since I want to improve the gameplay, I want the player to use the cursor with the mouse, but not moving freely: the cursor would move grid-snapped, just like the video above, got it?

Here's the code I attach to the cursor (I commented my mouse attempts):

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class userCursorController : MonoBehaviour {
 
 
     public float horizontalInput;
     public float verticalInput;
 
     //Mouse Variables
     private Vector3 mousePosition;
     public float moveSpeed = 0.1f;
 
     //Cursor move Variables
     private float moveRate = 0.15f;
     private float nextMove = 0.0f;
 
     //Use this for initialization
     void Start() {
         transform.Translate(1.0f, 1.0f, 0.0f);
         // Cursor.visible = false;
     }
 
     // Update is called once per frame
     void Update() {
         cursorMove();
        // mouseMovement();
        
 
 
 
     }
 
     void mouseMovement()
     {
       /*  Vector3 posicaoMouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         posicaoMouse.z = 0;
 
         Debug.Log("aaa " + posicaoMouse.x);
         */
         /* ( > gameObject.transform.localScale){ 
 
         gameObject.transform.position = posicaoMouse;
          } */
         }
     void cursorMove()
     {
 
         verticalInput = Input.GetAxis("Vertical");
         horizontalInput = Input.GetAxis("Horizontal");
 
         if(horizontalInput == 1.0f && nextMove < Time.time)
         {
 
            transform.Translate(1.0f, 0.0f, 0.0f);
             nextMove = Time.time + moveRate;
         }
         else if(horizontalInput == -1.0f && nextMove < Time.time)
         {
            transform.Translate(-1.0f, 0.0f, 0.0f);
             nextMove = Time.time + moveRate;
         }
 
         if (verticalInput == 1.0f && nextMove < Time.time)
         {
             transform.Translate(0.0f, 1.0f, 0.0f);
             nextMove = Time.time + moveRate;
         }
         else if (verticalInput == -1.0f && nextMove < Time.time)
         {
             transform.Translate(0.0f, -1.0f, 0.0f);
             nextMove = Time.time + moveRate;
         }
 
 
 
         
         
 
     }
 }
 

Thank you so much, guys!

Comment
Add comment · Show 4
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 toddisarockstar · Oct 04, 2018 at 04:21 PM 1
Share

another approach would be getting the mouse position and simply rounding it off

avatar image RockmanDeividu toddisarockstar · Oct 04, 2018 at 04:40 PM 0
Share

Hmmm, that's true!

avatar image RockmanDeividu toddisarockstar · Oct 05, 2018 at 12:25 PM 0
Share

Solved for me! Thanlks

avatar image RockmanDeividu · Oct 05, 2018 at 04:47 AM 0
Share

Got it, guys!

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Tilemaps;
 
 public class userCursorController : $$anonymous$$onoBehaviour {
 
 
     public float horizontalInput;
     public float verticalInput;
     
 
     //$$anonymous$$ouse Variables
     private Vector3 posicao$$anonymous$$ouse;
     public float moveSpeed = 0.1f;
     private int XRound; //convert $$anonymous$$ouse X to INT
     private int YRound;  //convert $$anonymous$$ouse X to INT
     private int checkY;
     private int checkX;
     private bool can$$anonymous$$oveY = true;
     private bool can$$anonymous$$oveX = true;
 
 
     //Cursor move Variables
     private float moveRate = 1.15f;
     private float next$$anonymous$$ove = 0.0f;
 
     //Use this for initialization
     void Start() {
       
         Cursor.visible = false;
        
 
     }
 
     // Update is called once per frame
     void Update() {
        // cursor$$anonymous$$ove();
         mouse$$anonymous$$ovement();
      
                 
     }
 
     public void mouse$$anonymous$$ovement()
     {
         Vector3 posicao$$anonymous$$ouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         posicao$$anonymous$$ouse.z = 0;
 
         // Debug.Log("aaa " + posicao$$anonymous$$ouse);
         XRound = (int)posicao$$anonymous$$ouse.x;
         YRound = (int)posicao$$anonymous$$ouse.y;
 
         Debug.Log("VV " + XRound + " BB " + YRound);
         if (next$$anonymous$$ove < Time.time)
         {
           
             transform.position = new Vector3((float)XRound, (float)YRound, 0);
             next$$anonymous$$ove = Time.time;
                       
 
         }
             }
     
   
 }
 

3 Replies

· Add your reply
  • Sort: 
avatar image
4

Answer by LCStark · Oct 04, 2018 at 04:04 PM

You can achieve that effect much easier - just use the "TileMap" class.

Add a new tilemap to your hierarchy (GameObject menu ->2D Object -> Tilemap), set it up to match the right size for your game. In your code first get your mouse position in world coordinates.

You can pass it to your tilemap to get the coordinates of the tile on your tilemap (as Vector3Int) using TileMap.WorldToCell method.

Then you can use those coordinates to get the world coordinates of the middle of that tile using Tilemap.GetCellCenterWorld. Use those to position your cursor.

Comment
Add comment · Show 6 · 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 RockmanDeividu · Oct 04, 2018 at 04:39 PM 0
Share

Darn, i don't get how to pass the coord. The Cursor is not a tile, it is a sprite. alt text

avatar image LCStark RockmanDeividu · Oct 04, 2018 at 04:46 PM 2
Share

Get your mouse position in world coordinates:

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);


Get the tile coordinates in your grid (tilemap):

Vector3Int cellCoords = yourTile$$anonymous$$ap.WorldToCell(mousePos);


Get the tile's center coordinates in world space:

Vector3 cursorPosition = yourTile$$anonymous$$ap.GetCellCenterWorld(cellCoords);


Use those on your "Cursor" sprite object:

cursor.transform.position = cursorPosition;

avatar image RockmanDeividu LCStark · Oct 04, 2018 at 07:41 PM 0
Share

Oh, thanks man!

But, still, it doesnt identify my tilemap. The script is component o Cursor.

I named the Tilemap "tile$$anonymous$$apa".

 public GameObject tile$$anonymous$$apa;
 
 [...]
 
  public void mouse$$anonymous$$ovement()
     {
         Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         Vector3Int cellCoords = tile$$anonymous$$apa.WorldToCell(mousePos);
 
 
     }

and it appears the error: "GameObject does not have a defitinion to WorldToCell, and theree was no method[...]

Show more comments
avatar image LCStark RockmanDeividu · Oct 04, 2018 at 05:59 PM 1
Share

Sorry, I didn't account for the fact that you're not using tiles in your game - this code will work only if there are any tiles under the cursor.

I do recommend you read more about this class, however, even if you don't want to use tiles in your gameplay. In my current project I'm using a single Tilemap filled with one sprite: a 1px border around an empty square sprite. That way I can display a grid in my game and have an easy access to those grid coordinates I gave you in the code before.

avatar image RockmanDeividu LCStark · Oct 04, 2018 at 07:48 PM 0
Share

Hmmm, got it. Thanks!

avatar image
0

Answer by RockmanDeividu · Oct 04, 2018 at 04:23 PM

Hmmm, didn't know that class. I'm gonna test it!

Thank you so much!

Comment
Add comment · 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
0

Answer by alpsaruhan96 · Nov 09, 2020 at 01:06 AM

use this to make your

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class crumov : MonoBehaviour {
  
      public float horizontalInput;
      public float verticalInput;
  
      //Mouse Variables
      public Vector3 mousePosition;
      public float moveSpeed = 0.1f;
      public Vector2 SquaresWeHaveMoved = Vector2.zero;
  
      //Cursor move Variables
      public float moveSize = 1f;
  
      //Use this for initialization
      void Start() {
          //transform.Translate(1.0f, 1.0f, 0.0f * Time.deltaTime);
          // Cursor.visible = false;
      }
  
      // Update is called once per frame
      void Update() {
          cursorMove();
         // mouseMovement();
  
      }
 
     void define()
      {
      // we are making a new var named SquaresWeHaveMoved then we are using that to get the movment done we are also using another var named moveSize. 
      //this is basicily the size of eacth square is in the grid
      // we are adding one to the Squares we have moved IF WE DID get more than 1 of what we hade it is hard to explain to me =(
      // we are basicily adding the x and the y of our mouse
      // after all that is put together IN CODE then this can work out =)
      // fill free to use this on your games ;)  
      }
  
 
          }
      void cursorMove()
      {
          //Debug.Log(SquaresWeHaveMoved.x, SquaresWeHaveMoved.y); 
          mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
          verticalInput = mousePosition.y;
          horizontalInput = mousePosition.x;
  
           if (verticalInput > (SquaresWeHaveMoved.y + 1)* moveSize)
           {
            transform.position=new Vector3(SquaresWeHaveMoved.x * moveSize, (SquaresWeHaveMoved.y +1) * moveSize,0).normzlized;  
            SquaresWeHaveMoved.y++;
           }
 
           if (verticalInput < (SquaresWeHaveMoved.y - 1)* moveSize)
           {
            transform.position=new Vector3(SquaresWeHaveMoved.x * moveSize, (SquaresWeHaveMoved.y -1) * moveSize ,0).normzlized;  
            SquaresWeHaveMoved.y--;
           }
 
           if (horizontalInput > (SquaresWeHaveMoved.x + 1)* moveSize)
           {
            transform.position=new Vector3((SquaresWeHaveMoved.x +1) * moveSize, SquaresWeHaveMoved.y * moveSize ,0).normzlized;  
            SquaresWeHaveMoved.x++;
           }
 
           if (horizontalInput < (SquaresWeHaveMoved.x - 1)* moveSize)
           {
            transform.position=new Vector3((SquaresWeHaveMoved.x +1) * moveSize , SquaresWeHaveMoved.y * moveSize ,0).normzlized;  
            SquaresWeHaveMoved.x--;
           }
          
       }
  
      
  }
Comment
Add comment · Show 2 · 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 alpsaruhan96 · Nov 09, 2020 at 01:07 AM 0
Share

use this to make your thing follow the mouse in grid style

avatar image alpsaruhan96 · Nov 09, 2020 at 01:12 AM 0
Share

actually this

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
 public class crumov : $$anonymous$$onoBehaviour
 {
  
      public float horizontalInput;
      public float verticalInput;
  
      //$$anonymous$$ouse Variables
      public Vector3 mousePosition;
      public float moveSpeed = 0.1f;
      public Vector2 SquaresWeHave$$anonymous$$oved = Vector2.zero;
  
      //Cursor move Variables
      public float moveSize = 1f;
  
      //Use this for initialization
      void Start() {
          //transform.Translate(1.0f, 1.0f, 0.0f * Time.deltaTime);
          // Cursor.visible = false;
      }
  
      // Update is called once per frame
      void Update() {
          cursor$$anonymous$$ove();
         // mouse$$anonymous$$ovement();
  
      }
 
     void define()
     {
     // we are making a new var named SquaresWeHave$$anonymous$$oved then we are using that to get the movment done we are also using another var named moveSize. 
     //this is basicily the size of eacth square is in the grid
     // we are adding one to the Squares we have moved IF WE DID get more than 1 of what we hade it is hard to explain to me =(
     // we are basicily adding the x and the y of our mouse
     // after all that is put together IN CODE then this can work out =)
     // fill free to use this on your games ;)  
      }
  
 
      void cursor$$anonymous$$ove()
      {
          //Debug.Log(SquaresWeHave$$anonymous$$oved.x, SquaresWeHave$$anonymous$$oved.y); 
          mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
          verticalInput = mousePosition.y;
          horizontalInput = mousePosition.x;
  
           if (verticalInput > (SquaresWeHave$$anonymous$$oved.y + 1)* moveSize)
           {
            transform.position=new Vector3(SquaresWeHave$$anonymous$$oved.x * moveSize, (SquaresWeHave$$anonymous$$oved.y +1) * moveSize,0).normalized;  
            SquaresWeHave$$anonymous$$oved.y++;
           }
 
           if (verticalInput < (SquaresWeHave$$anonymous$$oved.y - 1)* moveSize)
           {
            transform.position=new Vector3(SquaresWeHave$$anonymous$$oved.x * moveSize, (SquaresWeHave$$anonymous$$oved.y -1) * moveSize ,0).normalized;  
            SquaresWeHave$$anonymous$$oved.y--;
           }
 
           if (horizontalInput > (SquaresWeHave$$anonymous$$oved.x + 1)* moveSize)
           {
            transform.position=new Vector3((SquaresWeHave$$anonymous$$oved.x +1) * moveSize, SquaresWeHave$$anonymous$$oved.y * moveSize ,0).normalized;  
            SquaresWeHave$$anonymous$$oved.x++;
           }
 
           if (horizontalInput < (SquaresWeHave$$anonymous$$oved.x - 1)* moveSize)
           {
            transform.position=new Vector3((SquaresWeHave$$anonymous$$oved.x +1) * moveSize , SquaresWeHave$$anonymous$$oved.y * moveSize ,0).normalized;  
            SquaresWeHave$$anonymous$$oved.x--;
           }
      }
          
  }

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

149 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 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 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 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 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 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

Cursor Follow Script Causes Unpredictable Movement 0 Answers

Slime script? 1 Answer

Convert WASD to local rotation 1 Answer

How to make a Grid movement (tile per tile) 1 Answer

character(ball) rolls with less speed when I build it 2 Answers


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