unity, how works the RectTransformUtility.ScreenPointToLocalPointInRectangle() function - c#

I'm trying to follow this "tutorial":
http://forum.unity3d.com/threads/ui-follow-scene-objects.364143/
but the guy says that should use RectTransformUtility.ScreenPointToLocalPointInRectangle
I tried to do:
Vector2 localPoint;
RectTransformUtility.ScreenPointToLocalPointInRectangle(theRectTransformOfMyImage, transform.position, theCamera, out localPoint);
but the image goes to the corner screen, instead of being in the object...
any idea?
Edit:
More info, I have a 3D space, it's an enemy scene object with a following health bar image:
In the scripts, the variables are:
private Camera _camera;
private RectTransform _healthBarReact;
...
void Update()
{
// it works more or less, with the problem of "the UI element move at half the speed"
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(_camera, transform.position);
_healthBarReact.position = screenPoint;
// this doesn't work, the healthBar images goes to the screen corner
Vector2 localPoint;
RectTransformUtility.ScreenPointToLocalPointInRectangle(_healthBarReact, screenPoint, _camera, out localPoint);
_healthBarReact.position = localPoint;
}
the script is attached to the Enemy game object

Related

How to spawn a prefab in the position of the mouse cursor

Instantiate(clickPrefab, Input.mousePosition, Quaternion.identity);
this is the code what im using. I want to spawn a "1+" in the mousePosition. The Problem is, that the Prefab is not spawning in the correct location. In the scene view its spawning correct in the game view its spawning totaly random...
void scoreButtonOnClick()
{
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0;
Instantiate(clickPrefab, pos, Quaternion.identity);
money += dpc;
scoreText.text = money.ToString("#.##");
}`
this is my setup
https://i.imgur.com/NOtcITN.png
the Problem is now if I click with your code on my button the text is spawning not in the mouse position. Its spawning alwasy in the center.
https://i.imgur.com/niS3Pzt.png
Make sure you convert your mouse position from Screen to World cordinates with:
Camera.ScreenToWorldPoint.
Here's a minimal example, the Creator script is added to an empty GameObject on the scene. A prefab is manually assigned on the Editor.
public class Creator : MonoBehaviour
{
public GameObject prefab;
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Instantiate(prefab, Camera.main.ScreenToWorldPoint(Input.mousePosition), Quaternion.identity);
}
}
}
This assumes you have a single Ortographic Camera in your scene.
With this approach, objects don't appear on the game view, only on the scene:
This happens because when converting Screen to World coordinates, Unity takes the Camera Z position. So the prefabs are created right on top of the camera, and are not rendered. You can manually assign a Z value inside the camera range in order to avoid that:
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0;
Instantiate(prefab, pos, Quaternion.identity);

Unity: TopDown view - GameObject does not rotate toward mousepos

I've been doing some research on why my player(GameObject) is does not rotate toward my mouse position in my TopDown 3D game and I can't seem to find what is wrong with my code, so im making this post. The problem thats I have is that only the GameObject of my player (in my case, a capsule) rotate toward my mouse position but the axis of my player stays the same. In other word, I can't rotate the axis of my player, to face my mouse position, but I can rotate the GameObject of my player to face my mouse position. Its really hard to explain and this never happened to me before. Question is how can I rotate the axis of my player to face my mouse position. Keep in mind that my game is a top down view.
Here is the code im using for my playerMouvment and for my mouseLook:
public class Controller : MonoBehaviour
{
public float moveSpeed = 6;
Rigidbody rb;
Camera viewCamera;
Vector3 velocity;
void Start()
{
rb = GetComponent<Rigidbody>();
viewCamera = Camera.main;
}
void Update()
{
Vector3 mousePos = viewCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, viewCamera.transform.position.y));
transform.LookAt(mousePos + Vector3.up * transform.position.y);
velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized * moveSpeed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
Again I tried and look for any error in my code and I can't find anything that cause this weird situation and so if anyone can help me find a better way to write this code and solve my problem it would be great!
If I understand you correctly everything is fine with your game and the player is turning as it should, but only in the editor that the axis of the player (red, green and blue arrows) don't turn with the player?
If this is the problem it might be that you are using global space handle instead of local space. Clicking the icon I highlighted in the image should do the trick.
Use this code instead of LookAt() function
Vector2 direction = mousePos.position - player.transform.position;
player.transform.right /* Maybe you need Up or -Up or -right */ = direction;
This would work too in some cases
Vector2 direction = new Vector2
(
mousePos.position.x - player.transform.position.x,
mousePos.positoin.y - player.transform.position.y
)
player.transform.right /* Maybe you need Up or -Up or -right */ = direction;

Bullets not showing in Game view

I am making a simple 2d shooter in unity. I have made a prefab for my weapons and a script to shoot. When I enter the game mode I can see the bullet objects being created, but the bullets don't show on the screen. When I pause it and enter the scene mode they show (most of the time) any idea what could be causing this??
Here is the various settings on my bullet :
Thanks in advance for your help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
//variable to handle what progectile to spawn
public GameObject projectile;
//from where does the bullet coem from
public Transform shotPoint;
//How much time should be taken between shots
public float timeBetweenShots;
//time to shoot another bullet
private float shotTime;
// Update is called once per frame
private void Update()
{
//Callculating the the current mouse position to the current weapon position
//Input.mouse position returns a screenpoint
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = rotation;
//if the left mouse button is pressed
if(Input.GetMouseButton(0)){
//if the current time in the game is greater than the shot time
if (Time.time >= shotTime)
{
//shoot projectile
Instantiate(projectile, shotPoint.position, transform.rotation);
//recalculate shot time current time + time between shots
shotTime = Time.time + timeBetweenShots;
}
}
}
}
Check the order layer if you're by mistake not covering your bullets with the background image. Just make your bullet prefab layer higher then background equivalent.
Moreover, move the background node out of the scope of Player (currently you have it in the Player node), it should be equally set as your Main Camera and Player nodes in the tree. Then check the layering order and make sure order value in background is the lowest of all of your sprites.
Basically you are creating bullets inside of the weapon thats why you are not able to see your bullets. I create simple scene and adding sphere as a bullet then I realized sphere spawning in the gun(for me in the cube). If you will adding force everything will be okay.
Assume the shootPoint is somewhere over the gun barrel,
Instantiate(projectile, shotPoint.position, transform.rotation);
You should give them force,
GameObject projectile= Instantiate (prefab, position, rotation) as GameObject;
rb = projectile.GetComponent<Rigidbody>();
rb.AddForce (direction * speed);
Dont forget to add rigidbody to the bullet

Object rotation is not correct when rotating the camera

I have a camera which is showing the userInterface (canvas) object into the front of my camera. I am only updating my userinterface position if the camera raycast is not hitting my userInterface object collider. something like this
public class UIPlacerAtCamFront : MonoBehaviour {
public GameObject userInterface;
public float placementDistance;
Vector3 uiPlacementPosition;
RaycastHit objectHit;
void Update () {
Vector3 fwd = this.transform.TransformDirection(Vector3.forward);
//Debug.DrawRay(this.transform.position, fwd * 50, Color.green);
if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50))
{
//raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already
}
else
{
//raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera
uiPlacementPosition = this.transform.position + this.transform.forward * placementDistance;
userInterface.transform.position = uiPlacementPosition;
}
//Continuously update userInterface rotation according to camera
userInterface.transform.rotation = this.transform.rotation;
}
}
The above script has attached with my camera, it displaying the object correctly but as i start to rotate my camera my UI object rotation looks very strange as below image suggested
As i rotate, this problem occurs
I know that the problem is in rotation, so I tired to change my this rotation code
userInterface.transform.rotation = this.transform.rotation;
to this
userInterface.transform.localEulerAngles = new Vector3 (this.transform.localEulerAngles.x,
0,
this.transform.localEulerAngles.z);
but it bring another strange rotation for me, like given below
I want that my userinteface object face my camera correclty, even my camera watching the start or end of my userinteface object. How can i rotate my UI according to camera rotation correctly?
If I understand it correctly. You want a behavior similar to sliding google maps. Only that the camera has to rotate and the picture has to adjust its position and rotation for the behavior.
The following code should do that:
void Update() {
userInterface.transform.rotation = this.transform.rotation;
// Project camera to canvas plane
Vector3 projection = Vector3.ProjectOnPlane(this.transform.position - userInterface.transform.position, userInterface.transform.forward)
+ userInterface.transform.position;
// Get distance from camera to projected position (basically, distance from point to plane)
float curDistance = (this.transform.position - projection).magnitude;
// Correct that distance with desired distance
userInterface.transform.position += this.transform.forward * (placementDistance - curDistance);
}

How to attach the position/rotation of a GameObject to the position/rotation Camera

I'm working on the kinect V2, and i would like to make a script witch attaches the position of a game object ( moving with a head tracker) and the camera of my scene, to make an illusion of hologram.
I access it with the camera as a child of the game object, a lookat for a camera orbital ( rotation ), and a projection matrix for the camera to flip some axis of the camera.
But the projection matrix make some bugs with the textures and lighting of my scene. That´s why I would like to create a c# script who say:
Position camera = position gameobject (x,y,-z)
If position gameobject x>0 Else rotation camera y increase.
If position gameobject x<0 Else rotation camera y decrease.
If position gameobject y>0 Else rotation camera y decrease.
If position gameobject y<0 Else rotation camera y increase.
Nothing to do for the rotation camera z axis.
Can you help me to traduce this in C# ?
This is not my script :) but only the main idea i would like to do. I hope receive your help for a beginner developer!
Thank´s a lot
It is kind of hard to tell what you want. Here is some psuedo code that should help you on your way. I do not have unity to test it and it is not complete. But it will give you the basics to learn what you are trying to do.
using UnityEngine;
using System.Collections;
public class TestScript: MonoBehaviour {
public GameObject camera;
public GameObject gameObject;
public int rotationAmount = 1;
// Update is called once per frame
void Update () {
Vector3 camera = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, -gameObject.transform.position.x);
if(gameObject.transform.position > 0) {
camera.x -= rotationAmount;
}
camera.transform.position = camera;
}
}
You will have to name the C# script TestScript drag it on a GameObject and drag your camera and gameObject into its slots. If you do not know how to do this I suggest you read into Unity more.

Categories

Resources