How can i get mouse position click on terrain? - c#

The camera that the script is attached to is above high the terrain look on the terrain from the top. And now when i click the mouse i'm getting List points. But now i want to make that when i click the mouse it will give me the position on the terrain including terrain high places like hills.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetMousePosition : MonoBehaviour
{
private bool isMousePressed;
private List<Vector3> pointsList;
private Vector3 mousePos;
// Use this for initialization
void Start()
{
isMousePressed = false;
pointsList = new List<Vector3>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
isMousePressed = true;
pointsList.RemoveRange(0, pointsList.Count);
}
else if (Input.GetMouseButtonUp(0))
{
isMousePressed = false;
}
if (isMousePressed)
{
mousePos = GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
if (!pointsList.Contains(mousePos))
{
pointsList.Add(mousePos);
}
}
}
}

You would do this with a Raycast, you can cast a ray from the camera position to the terrain and then get all of the details you desire using the data that you get back.
So in your case if you wanted to add the hit point to the list you would do something like this
float distance = 100f;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
isMousePressed = true;
pointsList.RemoveRange(0, pointsList.Count);
}
else if (Input.GetMouseButtonUp(0))
{
isMousePressed = false;
}
if (isMousePressed)
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, distance))
{
if(!pointsList.Contains(hit.point)
{
pointsList.Add(hit.point);
}
}
}
}
It should be noted in the above example that Physics.Raycast has many overloads which allow you to customise how the ray fires. You can also use the hit and ray variables to get much more information such as the specific collider it hit as well as the world position at which the ray originated from, more information on how to do just that can be found in the Unity API documentation page for the Physics Raycast.
If you'd like to learn more about Raycasting I'd recommend watching the official Unity video on the topic which goes into further detail, you'll be using it a lot in game development so it's worth learning as much as you can about it before moving forward.

Related

Raycast goes backwards but the i code it to go forward

I try my best but my raycast still goes backwards every time - please I need help
Here's my code - basically the code shoots a raycast forward button to detected an enemy but instead the raycast goes the opposite way.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class milkscript: MonoBehaviour
{
NavMeshAgent Agent;
public Transform Point;
public float raydistance = 40f;
public float enemyview = 5f;
// Start is called before the first frame update
void Start()
{
Agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
RaycastHit Hit;
if(Physics.Raycast(Point.position,Point.position + Point.forward, out Hit, raydistance))
{
Debug.DrawRay(Point.position, Hit.transform.forward, Color.red);
Debug.Log(Hit.transform.name);
if(Hit.transform.tag == "chcolatemilk")
{
ChasePlayer(Hit.transform);
}
}
}
public void ChasePlayer(Transform target)
{
Agent.SetDestination(target.position);
transform.LookAt(target.position);
}
}
I think this is a combination of two issues
As mentioned your
Debug.DrawRay(Point.position, Hit.transform.forward, Color.red);
draws the ray in direction of Hit.transform.forward which is not the original direction you shoot your Raycast in
As a direction or the Raycast you are passing in
Point.position + Point.forward
which rather is a position.
You want to pass in only Point.forward as a direction
So it should rather be
void Update()
{
if(Physics.Raycast(Point.position, Point.forward, out var Hit, raydistance))
{
Debug.DrawLine(Point.position, Hit.transform.position, Color.red);
// TODO: remove this later! Logging every frame is quite expensive!
Debug.Log(Hit.transform.name);
// prefer "CompareTag" over "=="! It is a) slightly faster and b)
// instead of failing silently throws an error for typos and non-existent tags => better debugging live
if(Hit.transform.CompareTag("chcolatemilk"))
{
ChasePlayer(Hit.transform);
}
}
Debug.DrawRay(Point.position, Point.forward, Color.green);
}

Unity FollowMousePos

I build my first game and want to Instantiate an object,
the player should be allowed to choose where to instantiate it. It should be on the ground(plane) and the object(cube) should follow the mousePos. That's where the problem occurs. I tried for hours now (at least 5) but can't figure it out. I tried raycast and screentoWorld stuff, but the object doesn't follow my mouse perfectly. The best i could get is, if i moved right, the cube moved right, same for all the other directions but it did not move the same speed as my mouse, so it was not at the same pos and i can't "OnMouseDown" it(except for the very middle of the screen) I use an Orthographic Camera, the speed the Cube is moving with the mouse seems to be dependent on my camera Size, but I want it to work in any size etc. Thanks for any help in advance.
This is my code:
using UnityEngine;
using System;
public class VorKasernenBau : MonoBehaviour
{
public static event Action<Vector3> onBuildBuilding;
public Camera cam;
public GameObject kasernePrefab;
private void Update()
{
moveMe();
}
private void OnMouseDown()
{
if (true/*if genug platz*/)
{
Instantiate(kasernePrefab, transform.position, Quaternion.identity, transform.parent);
if (onBuildBuilding != null)
onBuildBuilding.Invoke(transform.position);
Destroy(gameObject);
}
}
private void moveMe()
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.CompareTag("Ground"))
{
transform.position = hit.point + Vector3.up;
Debug.Log("test");
}
}
}
}
Update1:
The z Position seems to be okay, but the xPos isn't following perfectly.
I moved the object with another function. (cam.screentoworld and y value to 1) This problem is solved(even known i am not really happy with this solution), but another problem comes with it. if i move the screen in play mode (through drag and drop), the mousePos is not calculated right since the calculated mousepos isn't translated like the screen. Anyways have a great night and thanks for the help.
Vector3 pos = cam.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(pos.x,1,pos.z);

Unity3D: How can i make my player go where i clicked with the mouse, without nav mesh agent?

I want to move my player around in my level without a NavMesh Agent.
I was thinking something about raycasting, but i have tried everything and even looked up videos and searched on google about it, can't seem to find anything that works
Plz help!
you can use this for moving to mouseclick position.
This method will move object or player to the position where mouse is clicked on screen.
sorry for syntax error i have typed directly here
using UnityEngine;
using System.Collections;
public class MouseMovement : MonoBehaviour
{
public float speed = 10f;
bool isplayermove = false;
// Use this for initialization
private void Start ()
{
Vector3 playerpos = transform.position;
}
// Update is called once per frame
private void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
is moveplayer = true;
}
if(ismoveplayer)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(input.mousepos.x,input.mousepos.y,input.mousepos.z);
transform.position = Vector3.MoveTowards(transform.position,new Vector3(mousepos.x,transform.position.y,mousepos.z),speed * time.deltatime);
if(transform.position == mousepos)
{
ismoveplayer = false;
}
}
}
}

Following instruction for drag and drop 3d object unity but not working

Hi so i have followed every instruction from youtube videos (https://m.youtube.com/watch?v=NMt6Ibxa_XQ) but in the game mode i still cant drag and drop my cube, the cube just stay still when i click and drag it. This problem really gave me a headache i’m pretty sure i have followed every detail from the video and repeat it over and over, thank’s for your time and help i really appreciate and need it, thank youi
in order for your cube to take the OnMouseDown() event you need to add a collider and rigidbody. click the cube, go to the properties on the right and click
add component - physics - cube collider
then do the same, for the rigid body
add component - physics - rigid body.
dont forget to set the rigidbody to kinematic, or set the gravity scale to 0 if you dont want it to fall out of the scene
use this script in order to drad and drop 3D Objects :
using UnityEngine;
using System.Collections;
public class DragAndDrop : MonoBehaviour
{
private bool _mouseState;
private GameObject target;
public Vector3 screenSpace;
public Vector3 offset;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
// Debug.Log(_mouseState);
if (Input.GetMouseButtonDown (0)) {
RaycastHit hitInfo;
target = GetClickedObject (out hitInfo);
if (target != null) {
_mouseState = true;
screenSpace = Camera.main.WorldToScreenPoint (target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
}
}
if (Input.GetMouseButtonUp (0)) {
_mouseState = false;
}
if (_mouseState) {
//keep track of the mouse position
var curScreenSpace = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
//convert the screen mouse position to world point and adjust with offset
var curPosition = Camera.main.ScreenToWorldPoint (curScreenSpace) + offset;
//update the position of the object in the world
target.transform.position = curPosition;
}
}
GameObject GetClickedObject (out RaycastHit hit)
{
GameObject target = null;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray.origin, ray.direction * 10, out hit)) {
target = hit.collider.gameObject;
}
return target;
}
}

Click to move code works in one scene but not the rest, NullReferenceException error

This is my click to move code, This is my first question, so I'm new to this. If you need any more information I will be happy to give it to you!
I have made a top-down dungeon game (Like Diablo), I completed creating all of the dungeon levels and started to animate and move my player, I got it working starting on the third and last level and it works perfect, I was happy as this is my first time making a game. I created a prefab of the character and moved it into the other levels and only got error when I clicked to move, I have tried to add them in separately but still didn't work sadly.
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour
{
public float speed;
public CharacterController controller;
private Vector3 position;
public AnimationClip idle;
public AnimationClip run;
public static Vector3 cursorPosition;
// Use this for initialization
void Start ()
{
position = transform.position;
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButton(0))
{
//Locate where the player clicked on the terrain
locatePosition();
}
//Move the player to the position
moveToPosition();
}
void locatePosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
if(hit.collider.tag!="Player"&&hit.collider.tag!="Enemy")
{
position = hit.point;
}
}
}
void locateCursor()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
cursorPosition = hit.point;
}
}
void moveToPosition()
{
//Game Object is moving
if(Vector3.Distance(transform.position, position)>1)
{
Quaternion newRotation = Quaternion.LookRotation(position- transform.position, Vector3.forward);
newRotation.x = 0f;
newRotation.z = 0f;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 10);
controller.SimpleMove(transform.forward * speed);
GetComponent<Animation>().CrossFade("run");
}
//Game Object is not moving
else
{
GetComponent<Animation>().CrossFade("idle");
}
}
}
As Catwood said, double clicking on the error in the console will take you to the relevant line of code that's causing the exception. I'd expect it to be one of the GetComponent calls though as you're trying to call the CrossFade function on something that might return null (in the case that the Animator component can't be found).
As a side note, you should avoid using GetComponent like this as it's inefficient. Instead, create a private / protected variable and store the reference when you first get the component.

Categories

Resources