Unity - Set player position after loading scene - unity3d

I am Trying to set player position after loading a scene. The program runs ok sometimes, but sometimes it places the player in the wrong position.
This is a video showing this strange behaviour: https://youtu.be/MFl9P3taV0Y
This is the code:
public class IniciaHeroi : MonoBehaviour
{
public GameObject GM;
private int startPosition;
void Awake()
{
startPosition = GM.GetComponent<StartScene>().startPosition;
if(startPosition == 1)
{
transform.position = new Vector3(119,4.67f,36);
transform.GetComponent<HeroiMovimento>().rot = -30;
Debug.Log("StartPosition1: " + transform.position);
}
if(startPosition == 2)
{
transform.position = new Vector3(49,13.8f,167);
transform.GetComponent<HeroiMovimento>().rot = 100;
Debug.Log("StartPosition2: " + transform.position);
}
}
}
Debug log shows always the correct position but, as you can see in the video, something changes the position.
Can anyone point the correct way to do this?

The problem was the Character controller attached to my player. For some strange reason Character Controller do not change its own transform.position when i change player transform.position.
So the solution is to disable Character Controller before change player position and Enable it after the change.

Thanks!! Having the same issue, and took me so long to find this. Finally I was able to solve by using disabling the Controller and then enabling it:
example:
gameObject.GetComponent<CharacterController>().enabled = false;
gameObject.transform.position = new Vector3(-31, 1, -10);
gameObject.GetComponent<CharacterController>().enabled = true;

Related

Unity OnMouseDrag triggered but all variations of Input.OnMouseButtonDown return false

I have a simple 3d object in my scene that I attached a script onto so I can rotate it freely in 3D space using mouse, the script attached is shown below:
float rotationSpeed = 6;
private void OnMouseDrag()
{
Debug.Log(Input.GetMouseButtonDown(0) + " 0");
Debug.Log(Input.GetMouseButtonDown(1) + " 1");
Debug.Log(Input.GetMouseButtonDown(2) + " 2");
if(Input.GetMouseButtonDown(0))
{
updatePrimitiveRotation();
}
}
private Vector2 getDragAmount()
{
Vector2 dragAmount = new Vector2(Input.GetAxis("Mouse X") * rotationSpeed,
Input.GetAxis("Mouse Y") * rotationSpeed);
return dragAmount;
}
private void updatePrimitiveRotation()
{
Vector2 drag = getDragAmount();
gameObject.transform.Rotate(Vector3.down, drag.x, Space.World);
gameObject.transform.Rotate(Vector3.right, drag.y, Space.World);
}
For some reason, the OnMouseDrag is always triggered as needed, but the shape never rotated! When I added the 3 debug lines they all result in false..
I was wondering if it was because I was using the buttons in my trackpad instead of a normal mouse, but searched into that and gathered that both work same, so I am not sure what the issue is here.
Another issue I just found is that my right mouse button never triggers the OnMouseDrag, it's only the left button (still all 3 debug lines output "false")
GetMouseButtonDown only returns true for the frame the button changed from released to pressed. GetMouseButton should do the trick.

How can I disable orientation with Oculus Locomotion Controller?

I am new to Unity and VR. I am working on a VR app using the Oculus Quest. I have set up a teleportation system based on the following tutorial video by Valem: https://www.youtube.com/watch?v=r1kF0PhwQ8E - but find that when I turn my head or use the thumbstick to oriented during teleportation, after landing I can be facing sideways and any further movement using the thumbstick appears to be incorrectly aligned - so when you try to move forwards you move sideways etc.
I presume my camera rig (which is a child of the OVRPlayerController) is facing the wrong way. This is backed up by the fact that some text I've placed in front of the rig appears to have shifted to the side instead of straight up front.
I just want a simple teleportation system so you move to the new location but do not orientate - instead you remain facing in the same direction as you started.
Is it possible to disable orientation? Or are there any recommended alternative solutions for a teleportation system?
i used this workaround to remove teleport orientation:
open TeleportDestination prefab
delete the orientation gameobject
hit play, then fix those scripts that referenced it
you'll also end up inside LocomotionTeleport.cs DoTeleport(), where it seems to set that teleport rotation (so probably enough if modify code here)
public void DoTeleport()
{
var character = LocomotionController.CharacterController;
var characterTransform = character.transform;
// removed orientation
//var destTransform = _teleportDestination.OrientationIndicator;
var destTransform = _teleportDestination.transform;
Vector3 destPosition = destTransform.position;
destPosition.y += character.height * 0.5f;
// removed orientation
//Quaternion destRotation = _teleportDestination.LandingRotation;// destTransform.rotation;
#if false
Quaternion destRotation = destTransform.rotation;
//Debug.Log("Rots: " + destRotation + " " + destTransform.rotation * Quaternion.Euler(0, -LocomotionController.CameraRig.trackingSpace.localEulerAngles.y, 0));
destRotation = destRotation * Quaternion.Euler(0, -LocomotionController.CameraRig.trackingSpace.localEulerAngles.y, 0);
#endif
if (Teleported != null)
{
//Teleported(characterTransform, destPosition, destRotation);
Teleported(characterTransform, destPosition, characterTransform.rotation);
}
characterTransform.position = destPosition;
//characterTransform.rotation = destRotation;
}

GameObject Follow cursor yet also follows enemies?

I'm making a simple character that follows the player's cursor. What I also want is for when the game object "enemy" appears the character then goes to that location to alert the player. Once the enemy is gone the character continues to follow the cursor like normal. Is there a reason why my script won't work. How else can I paraphrase it?
public class FollowCursor : MonoBehaviour
{
void Update ()
{
//transform.position = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
if (gameObject.FindWithTag == "Enemy")
{
GameObject.FindWithTag("Enemy").transform.position
}
if (gameObject.FindWithTag != "Enemy")
{
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
}
}
}
You are not using FindWithTag correctly, as it is a method that takes a string as parameter you need to use it like this:
GameObject.FindwithTag("Something") as stated in the Unity scripting API
Now to apply this to your code you would need to do the following to set your players position based on wether or not an enemy is found (assuming this script is on your actual player object):
if(GameObject.FindWithTag("Enemy"))
{
//If an enemy is found with the tag "Enemy", set the position of the object this script is attatched to to be the same as that of the found GameObject.
transform.position = GameObject.FindWithTag("Enemy").transform.position;
}
else
{
//when no enemy with the tag "Enemy" is found, set this GameObject its position to the the same as that of the cursor
transform.position = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
}
However this code will just snap your player instantly to the position of the found Enemy. If this is not the desired behaviour you could use a function like Vector3.MoveTowards instead to make the player move to it gradually.
This code also has room for optimisation as searching for a GameObject every update frame is not the ideal solution. But for now it should work.
I'm going to code coding all the function for you, I'm not pretty sure about the beavihour of your code, I understand a gameobject will be attached to the mouse position, so not really following....
Vector3 targetPosition;
public float step = 0.01f;
void Update()
{
//if there is any enemy "near"/close
//targetPosition = enemy.position;
//else
//targetPosition = MouseInput;
transform.position = Vector3.MoveTowards(transform.position, targetPosition , step);
}
For the f you can use a SphereCast and from the enemies returned get the closest one.

Unity2D: currentSelectedGameObject panel disabled

Okay, so I have a click to move game and a panel in which I do not want my player to move towards. However the panel is disabled at first (for an effect I'm doing) until the user clicks on a button to SetActive the panel. I used currentSelectedGameObject to block my player going to towards the panel but it isn't working, maybe because the panel was disabled in the first place, I not sure just spitting out ideas. Hopeful someone can help me.
using UnityEngine.EventSystems;
public GameObject currentSelectedGameObject;
public void Update () {
if (Input.GetMouseButtonDown (0)) {
if (EventSystem.current.currentSelectedGameObject)
return;
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 10; // distance from the camera
target = Camera.main.ScreenToWorldPoint (mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards (transform.position, target, speed * Time.fixedDeltaTime);
}
Thank you. :)
Use the button to setactive the panel and if not , you are not using the public GameObject currentSelectedGameObject variable in your code , do this :
if (EventSystem.current.currentSelectedGameObject == currentSelectedGameObject) // now this is your variable that you declared being used in the if statement
I cant remember correctly but mb its like this EventSystem.current.currentSelectedGameObject.name

Firing on both side Unity 2D

I am trying to make a 2D platformer but my player is not firing on both side I don't know what is wrong with my script.
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
public float bulletSpeed;
public GameObject bullet;
public Transform bulletX;
GameObject clone;
void Update ()
{
if (Input.GetKeyUp ("space"))
{
clone = Instantiate(bullet,new Vector3(bulletX.position.x,bulletX.position.y+0.1f,0f),Quaternion.identity) as GameObject;
if (GameObject.Find ("Player").GetComponent<Player> ().left == true)
bulletSpeed = -30f;
else
bulletSpeed = 30f;
}
bullet.rigidbody2D.velocity = new Vector2(bulletSpeed * 0.5f, 0f);
Destroy (clone, 1f);
}
}
I tried to increase velocity inside the if condition but bullet was moving faster than I needed.
I think your question was very hard to understand what you want to accomplish, but I can see some errors in your code that will render the "clone" you are creating, useless.
The update loop is continuously executing, and you have placed the destroy outside your "Press space" code block. Unity tries to destroy it every frame. Place it inside the space.
I feel it should look more like this:
if (Input.GetKeyUp ("space"))
{
clone = Instantiate(bullet,new Vector3(bulletX.position.x,bulletX.position.y+0.1f,0f),Quaternion.identity) as GameObject;
if (GameObject.Find ("Player").GetComponent<Player> ().left == true)
bulletSpeed = -30f;
else
bulletSpeed = 30f;
bullet.rigidbody2D.velocity = new Vector2(bulletSpeed * 0.5f, 0f);
Destroy (clone, 1f);
}
This might not answer your question, but could you specify more what behaviour you are after? And what object is this script running on? (It is called Bullet with a field referance to another bullet ?)
Debug.Log your bulletSpeed * 0.5f
If I am correct. Even if your Player is Looking at the other way. It is returning
an ABS number meaning (bulletSpeed = -30f & 0.f is != -44954 something but == 44954).
Alternatively you can use AddForce instead of Velocity. It is easier to control.
QUESTION. Why not use Instantiate Vector2?