Skip to content

Instantly share code, notes, and snippets.

@jcordeiro67
Last active February 8, 2017 23:11
Show Gist options
  • Save jcordeiro67/be466f243be9d012d515154cf84fe26c to your computer and use it in GitHub Desktop.
Save jcordeiro67/be466f243be9d012d515154cf84fe26c to your computer and use it in GitHub Desktop.
Alternate Code for CalculateWorldPointOfMouseClick
/* DESCRIPTION:
* Spawns defenders on the grid by converting
* mouse position when clicked on screne to world cordinates.
* Rounds the world cordinates to a whole gid number and
* spawns a defender in that location.
*
* Collider2D:
* Used for getting OnMouseDown message
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DefenderSpawner : MonoBehaviour {
void OnMouseDown(){
Vector2 rawPos = CalculateWorldPointOfMouseClick ();
Vector2 roundedPos = SnapToGrid (rawPos);
Instantiate (DefenderButton.selectedDefender, roundedPos, Quaternion.identity);
// Nested methods to convert and round the mouse click position
//print (SnapToGrid (CalculateWorldPointOfMouseClick ()) );
}
Vector2 SnapToGrid(Vector2 rawWorldPos){
// Rounds the click to the nearest integer
// Returns Vector2 with newX, newY
float newX = Mathf.Round (rawWorldPos.x);
float newY = Mathf.Round (rawWorldPos.y);
return new Vector2 (newX, newY);
}
Vector2 CalculateWorldPointOfMouseClick(){
// Converts the mousePosition to world cordinates
// Returns Vector2 (mousePosX, mousePosY)
Camera camera = GameObject.FindObjectOfType<Camera> ();
Vector3 mousePos = camera.ScreenToWorldPoint (Input.mousePosition);
return new Vector2 (mousePos.x, mousePos.y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment