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.
Related
OBJECTIVE
I am using this script I got from Unity's forums to move my camera around. It works perfectly and this is exactly the style of camera I want. Here it is in action:
https://streamable.com/j7ozps
I wanted to create a zoom effect when the user holds the right mouse button.
PROBLEM
After zooming in, the aim is off by a lot. Here's what happens:
https://streamable.com/8aiil0
MY ATTEMPT
void Update () {
if (Input.GetMouseButton(1))
{
int layerMask = 1 << CombatManager.GROUND_LAYER; // -> public const int GROUND_LAYER = 8;
Ray mouseClick = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hitInfos;
float maxDistance = 100.0f;
hitInfos = Physics.RaycastAll(mouseClick, maxDistance,
layerMask, QueryTriggerInteraction.Ignore);
mainCamera.fieldOfView = 10;
mainCamera.transform.LookAt(hitInfos[0].point);
}
else
mainCamera.fieldOfView = startingFieldOfView;
I also tried swapping the order of the LookAt and field of view assignment.
What am I doing wrong?
Seems that what you want is to zoom towards the cursor position, not towards where the ray hits which are likely not the same point. To check that out you can draw a debug cube where the ray hits, to check if the point you are looking at is the one you need, like so:
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hitInfos[0].point;
Check Camera.ScreenToWorldPoint that gives you the worldspace point created by converting the screen space point at the provided distance z from the camera plane.
What I would try:
Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//check if this is the point you want to look at
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = point;
//look at it
mainCamera.transform.LookAt(point);
It should not mind if you are using the cam.nearClipPlane or the cam.farClipPlane in the ScreenToWorldPoint function, but I would play with that in case something is not working as intended.
Vector3 screenPoint = Input.mousePosition;
screenPoint.z = Camera.main.farClipPlane;
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);
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);
I am currently creating a game in Unity, in which you move a ball around using OnMouseDrag(), a CircleCollider2D and a RigidBody2D. This is how I set the position of the ball:
private void OnMouseDrag()
{
Vector2 mouseInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
playerRb.position = new Vector3(mouseInWorld.x, mouseInWorld.y, 0);
}
I still want the ball to slide on collision while the mouse moves around. Is there a way to do this?
I have tried RigidBody2D.MovePosition(), but the ball jumped around from one point to another, and Raycasts but couldn't get that to work either.
EDIT:
This is what I've got now:
playerRb.velocity = new Vector3(mouseInWorld.x - playerRb.position.x, mouseInWorld.y - playerRb.position.y, 0);
Now the problem is, that the ball lags behind the mousePosition.
When you use RigidBody.MovePosition, you don't call the physics engine and so it ignores collisions. If you want collisions to happen you need to use RigidBody.Velocity instead.
Doing this change will require you to make some change to your code though because what you give to RigidBody.Velocity is a velocity and not a position so you will need to calculate the velocity required in x,y (and z if you are in 3d) to reach your destination.
I invite you to read the Unity page about velocity for more info
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
Note: This will make the player/ball stick to collisions.
Modifying the velocity could cause the ball to bounce around unexpectedly when the ball collides with the wall. I would use a CircleCast for this, check if it hit anything, then use MovePosition accordingly:
float cursorDepth;
Rigidbody2D playerRb;
CircleCollider cc;
void Awake()
{
playerRb = GetComponent<Rigidbody2D>();
cc = GetComponent<CircleCollider>();
}
private void OnMouseDrag()
{
Vector2 mouseInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 posToMouse = mouseInWorld - playerRb.position;
RaycastHit2D hit = Physics2D.CircleCast(playerRb.position,
cc.radius * transform.lossyScale.x, posToMouse, posToMouse.magnitude);
if (hit.collider != null)
{
mouseInWorld = hit.centroid;
}
playerRb.MovePosition(mouseInWorld);
}
But notice that if the ball can't move all the way to the mouse, it might cause the drag to end. So, plan accordingly.
I have a sphere in that is moving foward and I need it to follow my finger smoothly when it swipes on the screen but only in the x axis.
I trying to make the exact movent like Rolling Sky, Color Road
The ball Should follow my finger when it swipes in the x axis and move smoothly.
Just like in the games I mention before.
I try OnMouseDrag and a lot of ways but it dont work correctly beacuse it dont dont follow the finger or it dont move while finger is swiping.
From what I understand, it seems you want to get the position of the user's finger and move the ball accordingly?
You could achieve this with Touch.position
Example:
private void Update()
{
Touch touch = Input.GetTouch(0); // Get the touch data for the first finger
Vector2 position = touch.position; // Get the position in screen-space
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(position); // Convert the position to world space
Vector3 ballPosition = ball.transform.position;
ball.transform.position = new Vector3(worldPosition.x, ballPosition.y, ballPosition.z); // Move the ball
}
I think you should handle the input separately from the sphere.
Put this on a script to detect the swiping on the screen.
bool inputBegan = false;
Vector2 beganPosition;
void Update()
{
if (!inputBegan && Input.GetMouseButtonDown (0))
{
inputBegan = true;
beganPosition = Input.mousePosition;
}
else if (inputBegan && Input.GetMouseButtonUp (0))
{
//If you want a threshold you need to change this comparison
if (beganPosition.x > Input.mousePosition)
{
MoveBallLeft ();
}
else
{
MoveBallRight ();
}
inputBegan = false;
}
}
The movement of the balls you can achieve it adding or substracting Vector2.right * movingDistance to the sphere Transform if you want it to teleport or making the sphere move slowly using a targetPosition and currentPosition and each Update cycle add a little bit of transform distance.
I solved it doing this and setting the variable NavigationMultiplier to 10000
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.