I'm trying to have various interactions take place when looking at a game object, but it doesn't seem to work when I'm too close. I'm using Unity's first person controller and the script it attached to the camera.
void Update () {
RaycastHit hit;
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
if(Physics.Raycast(transform.position,(forward), out hit) ){
GameObject lookingAt = hit.collider.gameObject;
if (lookingAt.layer == 9)
{
Debug.Log("This doesn't always show up.");
}
}
}
I put
public LayerMask interactionLayers = ~0;
And selected the elements that should be detected in the inspector. That seemed to fix the issue.
Thanks.
Related
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);
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;
}
}
Okay so I've been fighting with this script for a couple days now. I've made progress in other aspects but I can't seem to get my enemies to properly chase the player character.
The script is supposed to have the enemies wander until an empty child 'eyes' sees the player. Then it should start chasing the player. Think pac-man. What it's doing right now is making one loop of it's wander cycle and then stopping and not seeing the player at all.
This is the code that I've got so far for that script -
using UnityEngine;
using System.Collections;
public class dudeFollow : MonoBehaviour {
Transform tr_Player;
float f_MoveSpeed = 3.0f;
private DudeMove moveScript;
public Transform eyes;
public float sightRange = 3f;
// Use this for initialization
void Start () {
tr_Player = GameObject.FindGameObjectWithTag("Player").transform;
moveScript = GetComponent<DudeMove>();
}
// Update is called once per frame
void Update () {
RaycastHit hit;
if (Physics.Raycast (eyes.transform.position,eyes.transform.forward, out hit,sightRange) && hit.collider.CompareTag ("Player")) {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
moveScript.enabled = false;
}
}
}
Any help or tips would be appreciated.
Because you have 2D game, what most likely happens is your enemy wonders away on z-axis as well, but because it's 2D, you can't see it. So switch to 3D mode in your main scene window and see if that's the case.
If it is, just reset z-axis to 0 on every frame and disable angular momentum :) I had this happen with 2D games.
void Update () {
RaycastHit hit;
if (Physics.Raycast (eyes.transform.position,eyes.transform.forward, out hit,sightRange) && hit.collider.CompareTag ("Player")) {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
moveScript.enabled = false;
}
transform.position.z = 0; // or something along those lines, I don't remember the syntax exactly.
}
I have and raycast, and a rayCastHit. Whenever the user click on the fire button. It will move the FPS charater to the location where the rayCastHit is. lightRetical is a gameObject variable which is a spotlight that shows where the rayCastHit is.
The Funny thing is, it works when I click play in unity. But whenever I build to my android phone it doesn't work. I am unable to move the fps character.
The FPS character I used, is from the standard asset "character" and the codes I add them to the Update() method.
RaycastHit seen;
Ray raydirection = new Ray(transform.position, cam.transform.forward);
int sightlength = 5;
if (Physics.Raycast(raydirection, out seen, sightlength))
{
if (seen.collider.tag == "Floor" && Input.GetButtonDown("Fire1")) //in the editor, tag anything you want to interact with and use it here
{
Vector3 relativePoint;
lightRetical.SetActive(true);
relativePoint = seen.point;
relativePoint.y = 2.0f;
bodychar.transform.position = relativePoint;
}
else
{
lightRetical.SetActive(true);
Vector3 relativePoint;
relativePoint = seen.point;
relativePoint.y = 2.64f;
lightRetical.transform.position = relativePoint;
}
}
else
{
lightRetical.SetActive(false);
}
I suggest casting the ray from the camera position forward. If the player rotates his head the raycast will follow. I'm currently developing an app for VR and this seems like the best solution. You can use collision layers to filter the raycast. I would also print the hit.transform to the console, to check what the raycast is hitting. Hope this helps.
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.