Unity 3d Rigidbody moving but not child object - unity3d

I have made a car scene in Unity. I have one Rigidbody (car) and its childgameobject. I made a script to move that childgameobject with sliders while Rigidbody is moving. The childgameobject moves fine with the slider but when my Rigidbody moves, the child GameObject remains in the same position and doesn't move with Rigidbody. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChildMove : MonoBehaviour
{
public Slider MySliderx;
public Slider MySlidery;
public Slider MySliderz;
public Transform Cam;
public float temp;
private float CamInitialY = 0f;
private float CamInitialX = 0f;
private float CamInitialZ = 0f;
// Use this for initialization
void Start () {
CamInitialY = Cam.transform.position.y;
CamInitialX = Cam.transform.position.x;
CamInitialZ = Cam.transform.position.z;
}
// Update is called once per frame
void Update () {
Cam.transform.position = new Vector3 (Cam.position.x, CamInitialY + MySliderx.value , Cam.position.z);
Cam.transform.position = new Vector3 (CamInitialX + MySlidery.value, Cam.position.y, Cam.position.z);
Cam.transform.position = new Vector3 (Cam.position.x, Cam.position.y, CamInitialZ + MySliderz.value);
}
}

Fixed by changing position to localposition.

Related

unity2d move a game object towards a random position

i have a satellite which i let spawn randomly in a different script by just using the method Satellite() and i want it move towards the bottom of the screen but not towards the middle but again a random position of the ground. the problem is that satellitedirection is always 0. also, if i somehow would manage to get the problem solved, wouldn´t every satellite on the screen move towards the same position?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SatelliteBehaviour : MonoBehaviour
{
[SerializeField] Rigidbody2D satelliteRB;
[SerializeField] Transform satelliteFirePoint;
[SerializeField] GameObject satellitePrefab;
float satellitedirection;
void Start()
{
}
void Update()
{
transform.Rotate(0,0,80*Time.deltaTime);
//satelliteRB.velocity = -transform.up * 5;
transform.position = Vector2.MoveTowards(transform.position, new Vector2(satellitedirection, -15), 1 * Time.deltaTime);
Debug.Log(satellitedirection);
}
public void Satellite()
{
Instantiate(satellitePrefab, new Vector2(Random.Range(-18,18),10), Quaternion.identity);
satellitedirection = Random.Range(-18, 18);
}
}
The Instantiate() method returns a game object but it is not assigned to anything. Assign a var and set its position and rotation.
GameObject satelliteObj = Instantiate(satellitePrefab, new Vector2(Random.Range(-18,18),10), Quaternion.identity);
// random rotation
satelliteObj.transform.rotation = Quaternion.Euler(new Vector2(Random.Range(-180, 180), Random.Range(-180, 180)));

How do I make a camera that points towards where the player is going and is back and up and pointed down?

it is a ball that actally rolls so I can't just put a child camera on with an offset and call it a day so instead I created this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera : MonoBehaviour
{
public GameObject Player;
public Vector3 lastpos;
public Vector3 cameraxyz;
public Vector3 camerarotationxyz;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 currentDirection = Player.transform.position - lastpos;
transform.rotation = Quaternion.LookRotation(currentDirection-camerarotationxyz);
transform.position = currentDirection + cameraxyz;
Vector3 lastPos = Player.transform.position;
}
}
and attached it to an empty game object made the game object a child of the ball and then made the camera a child of the empty game object
which half works the empty game object will all always rotate to have it's z axis aligned with the origin meaning the offset for the camera is wrong and it won't look at where the ball is going but will look towards the ball
this is how I set the hierarchy up (I put the script on the empty game object)
https://i.stack.imgur.com/sbiMt.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera : MonoBehaviour
{
public GameObject Player;
public Vector3 lastPos;
public Vector3 cameraxyz;
public Vector3 camerarotationxyz;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 currentDirection = Player.transform.position - lastPos;
transform.rotation = Quaternion.LookRotation(currentDirection - new Vector3(0,currentDirection.y,0));
Vector3 newPosition = currentDirection + cameraxyz;
transform.position = newPosition;
lastPos = Player.transform.position;
transform.position = Player.transform.position;
}
}
taking the Vector3 off of lastPos and capitalizing mistakes leads to a gameobject with an incorrect offset and rotation to stop it traking the y axis (as I can change which whay is up and change the y to be parrallel to gravity using an external script) I did (currentDirection - new Vector3(0,currentDirection.y,0) the new Vector3 is needed and so are the zeros as a float nor int cannot be use to subtract from a Vector3 then I did transform.position = Player.transform.position; so that the empty game object is correctly put on the ball then to get the camera to move with the correct offset I made the camera a child of the emptygameobject

Rotating a child gameobject relative to immediate parent

Hi everybody, I'm trying to rotate a child game object relative to another child game object. For example, as shown in this heirarchy below, I'm trying to rotate PA_DroneBladeLeft (and PA_DroneBladeRight) with respect to their immediate parents PA_DroneWingLeft (and PA_DroneWingRight) respectively. I want these blades to spin in place. Instead I'm getting them to spin globally in the y-direction relative to the main parent (Air Drone). I would think that the line in Update method that I commented out should have worked, and it did but it still rotated relative to Air Drone and not in place. The second line, RotateAround method I've tried to create an empty game object called Left Pivot and put it approximately in the center of the left wing and have the left blade rotate around that, but it was no use.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftBladeRotation : MonoBehaviour
{
GameObject leftBlade;
private float speed;
private float angle;
GameObject leftPivot;
// Start is called before the first frame update
void Start()
{
speed = 10f;
leftBlade = transform.Find("PA_DroneBladeLeft").gameObject;
angle = 0f;
leftPivot = GameObject.FindGameObjectWithTag("Air Drone").transform.Find("PA_Drone").transform.Find("PA_DroneWingLeft").transform.Find("Left Pivot").gameObject;
}
// Update is called once per frame
void Update()
{
angle += speed * Time.deltaTime;
Quaternion rotation = Quaternion.Euler(new Vector3(0f, angle, 0f));
//leftBlade.transform.localRotation = rotation;
leftBlade.transform.RotateAround(leftPivot.transform.localPosition, Vector3.up, angle);
}
}
This is your script with some little changes. It actually works when I attached it on the blade gameObject.
using UnityEngine;
public class BladeRotate : MonoBehaviour
{
private float _speed;
private float _angle;
private void Start()
{
_speed = 400f;
_angle = 0f;
}
private void Update()
{
_angle += _speed * Time.deltaTime;
var rotation = Quaternion.Euler(new Vector3(0f, _angle, 0f));
transform.localRotation = rotation;
}
}
The second line does not work because you rotate the blade around global y-axis by Vector3.up
Here is an alternative. Attach the following script on your blades.
using UnityEngine;
public class BladeRotate : MonoBehaviour
{
[SerializeField] private int speed = 400;
private Transform _transform;
private void Start()
{
_transform = transform;
}
private void Update()
{
transform.RotateAround(_transform.position, _transform.up, speed * Time.deltaTime);
}
}

How to make spawn canvas with render camera?

UNITY 2D C#
I have a Canvas object.
My Canvas is image (ARROW) that indicates target (STAR).
When a STAR hit the PLAYER,it is destroyed.
Unfortunately, I can not turn off the ARROW and (when STAR respawn) turn on it again, because after appearing ARROW indicates the previous target.
That's why I must to destroy the canvas.
I added a script to the STAR :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyTest : MonoBehaviour {
public SpawnStar other;
public GameObject Spawner;
public GameObject ToDestroy;
void Awake (){
GameObject Spawner = GameObject.Find ("Spawner");
other = Spawner.GetComponent<SpawnStar>();
}
void OnCollisionEnter2D (Collision2D coll){
if (coll.gameObject.tag == "Player") {
Destroy (gameObject);
Debug.Log("DestroyedStar");
GameObject ToDestroy = GameObject.Find ("Window_QuestPointer");
Destroy (ToDestroy);
Debug.Log("DestroyedOptionOne");
other.Start ();
}
}
}
I added a script to the CANVAS:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CodeMonkey.Utils;
public class Window_QuestPointer : MonoBehaviour {
[SerializeField] private Camera uiCamera;
public SpawnStar other;
public GameObject Spawner;
private Vector3 targetPosition;
private RectTransform pointerRectTransform;
void Awake (){
GameObject Spawner = GameObject.Find ("Spawner");
other = Spawner.GetComponent<SpawnStar>();
other.Start ();
}
private void Start ()
{
targetPosition = GameObject.FindWithTag("Star").transform.position;
pointerRectTransform = transform.Find ("Pointer").GetComponent<RectTransform> ();
}
private void Update (){
Vector3 toPosition = targetPosition;
Vector3 fromPosition = Camera.main.transform.position;
fromPosition.z = 0f;
Vector3 dir = (toPosition - fromPosition).normalized;
float angle = UtilsClass.GetAngleFromVectorFloat(dir);
pointerRectTransform.localEulerAngles = new Vector3 (0, 0, angle);
float borderSize = 40f;
Vector3 targetPositionScreenPoint = Camera.main.WorldToScreenPoint (targetPosition);
bool isOffscreen = targetPositionScreenPoint.x <= borderSize || targetPositionScreenPoint.x >= Screen.width - borderSize || targetPositionScreenPoint.y <= borderSize || targetPositionScreenPoint.y >= Screen.height - borderSize;
Debug.Log (isOffscreen + " " + targetPositionScreenPoint);
if(isOffscreen){
Vector3 cappedTargetScreenPosition = targetPositionScreenPoint;
cappedTargetScreenPosition.x = Mathf.Clamp (cappedTargetScreenPosition.x, borderSize, Screen.width - borderSize);
cappedTargetScreenPosition.y = Mathf.Clamp (cappedTargetScreenPosition.y, borderSize, Screen.height - borderSize);
Vector3 pointerWorldPosition = uiCamera.ScreenToWorldPoint (cappedTargetScreenPosition);
pointerRectTransform.position = pointerWorldPosition;
pointerRectTransform.localPosition = new Vector3 (pointerRectTransform.localPosition.x, pointerRectTransform.localPosition.y, 0f);
}
else{
Vector3 pointerWorldPosition = uiCamera.ScreenToWorldPoint (targetPositionScreenPoint);
pointerRectTransform.position = pointerWorldPosition;
pointerRectTransform.localPosition = new Vector3 (pointerRectTransform.localPosition.x, pointerRectTransform.localPosition.y, 0f);
}
}
}
I added a script to the SPAWNER object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnStar : MonoBehaviour {
private int waveNumber = 0;
public int enemiesAmount = 0;
public GameObject star;
public GameObject option;
public Camera cam;
public GameObject objectToEnable;
// Use this for initialization
public void Start () {
StartCoroutine (StarEnable());
cam = Camera.main;
enemiesAmount = 0;
objectToEnable.SetActive (false);
}
// Update is called once per frame
public IEnumerator StarEnable () {
yield return new WaitForSeconds (10f);
float height = cam.orthographicSize + 1; // now they spawn just outside
float width = cam.orthographicSize * cam.aspect + 1;
if (enemiesAmount==0) {
Instantiate(star, new Vector3(cam.transform.position.x + Random.Range(-width, width),3,cam.transform.position.z+height+Random.Range(10,30)),Quaternion.identity);
enemiesAmount++;
Instantiate (option, transform.position, transform.rotation);
objectToEnable.SetActive (true);
}
}
}
In addition, the ARROW must respawn in the screen and the STAR off the screen.
you shouldn't destroy a canvas or any GameObject during runtime, answering your question, when you Instantiate the canvas prefab, set the renderer camera with
canvas.worldCamera, but you can, instead of destroying your canvas, create a container inside of it put all the GameObjects inside of this GameObject container, and activate and deactivate it when needed.
If you have one camera U can attach simple script which finds Canvas commonent and attach camera to it in Start() for example:
public class AttachCamera: MonoBehavour
{
private void Start()
{
gameObject.GetComponent<Canvas>().worldCamera = Camera.main;
}
}
If there are more than one camera U have to remember attached camera and set it mannualy after Canvas was spawned.
Can you please show your code that is responsible for destroying the Canvas?
I would use another GameObject that handles this gameplay logic.
First, I would use cameraObj.SetActive(false); to disable the camera, and not destroy it. Destroying and Creating objects can cause memory issues sometimes, and it's just not good practice unless absolutely necessary.
Then, use a Coroutine and WaitForSeconds() or something to that effect to wait, and then call cameraObj.SetActive(true) to re-enable your Camera's main GameObject.

All objects in game vibrates(shakes) back and forth while moving player. How can I make it smooth?

I am new to unity, I searched for this problem but couldn't find satisfactory answer.
I have cube as player with rigidbody (gravity deactivated) attached
and few other big cubes as buildings
and camera attached to player.
When I move player with arrow keys, it moves smoothly but all other objects vibrates, as I increase the speed of player ground and buildings stars vibrating more and more.
My Player Script:-
using UnityEngine;
using System.Collections;
public class playerController : MonoBehaviour {
public Rigidbody player;
public float speed;
private Vector3 vect;
// Use this for initialization
void Start () {
player = GetComponent<Rigidbody> ();
}
void Update () {
float moveH = Input.GetAxis ("Horizontal");
float moveV = Input.GetAxis ("Vertical");
vect = new Vector3 (moveH,0.0f,moveV);
}
void FixedUpdate () {
player.velocity = vect*speed;
}
}
2] My camera script:-
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public Transform player;
public GameObject cameraa;
private Vector3 offset;
public float speed;
void Start () {
//calculating offset
offset = cameraa.transform.position - player.position;
}
// Update is called once per frame
void FixedUpdate () {
cameraa.transform.position = player.position + offset;
}
}
In camera I tried Update(), FixedUpdate() and LateUpdate()
but effect was nearly same and not smooth.
How can I make gound and other object move smoothly??
You can avoid player from vibrating by changing the Bounce-Threshold value in physics settings b (edit > project-settings > physics > Bounce-Threshhold) to something like 8