- Home /
RaycastHit2D Issue
Hello, I am doing a Unity course and it is using a version without the tile palette, I am assuming this is what is causing the problem but am too new to figure out what is happening. So I am trying to place a tower and the raycasthit2d transform position is returning 0.0,0.0,0.0 as opposed to the mouse location. The worldPoint is returning correct values but the hit.transform.position is returning rubbish. Please see my code below. Any help with this would be greatly appreciated. Thanks.
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)){
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("Vector2 Values: " + worldPoint);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
Debug.Log("RaycastHit2D Values: " + hit.transform.position);
if (hit.collider.tag == "BuildSites"){
placeTower(hit);
}
}
}
public void placeTower(RaycastHit2D hit){
if(!EventSystem.current.IsPointerOverGameObject()&& towerBtnPressed != null){
GameObject newTower = Instantiate(towerBtnPressed.TowerObject);
newTower.transform.position = hit.transform.position;
}
}
public void selectedTower(TowerBtn towerSelected){
towerBtnPressed = towerSelected;
}
}
Answer by Cornelis-de-Jager · Nov 20, 2018 at 01:49 AM
I assume what is happening is you are aiming at the world/Terrain - which is probably spawned at Vector2.Zero. The Transform position is NOT the point you hit. Think of it this way ~ If you click on the edge of a cube/sqaure. The point of hit is on the edge, but the position of the cube/sqaure's Transform is the middle of it.
So Instead of using the transform.position get the point you hit.
void Update () {
if (Input.GetMouseButtonDown(0)){
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("Vector2 Values: " + worldPoint);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
Debug.Log("RaycastHit2D Values: " + hit.point);
if (hit.collider.tag == "BuildSites"){
placeTower(hit);
}
}
}
public void placeTower(RaycastHit2D hit){
if(!EventSystem.current.IsPointerOverGameObject()&& towerBtnPressed != null){
GameObject newTower = Instantiate(towerBtnPressed.TowerObject);
newTower.transform.position = hit.point;
}
}
Wow! That single line of code was making my $$anonymous$$d explode. Thanks a lot! It worked without a problem. At least now I know how to deal with this kind of troubles. I really, really appreciate your help.
Your answer