Question by
Chocolade · Apr 07, 2018 at 10:13 AM ·
c#scripting problemscript.
How can I change the object rotatearound radius in real time while the game is running in the Update ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetBehaviour : MonoBehaviour
{
// Add this script to Cube(2)
[Header("Add your turret")]
public GameObject Turret;//to get the position in worldspace to which this gameObject will rotate around.
[Header("The axis by which it will rotate around")]
public Vector3 axis;//by which axis it will rotate. x,y or z.
[Header("Angle covered per update")]
public float angle; //or the speed of rotation.
public float upperLimit, lowerLimit, delay;// upperLimit & lowerLimit: heighest & lowest height;
private float height, prevHeight, time;//height:height it is trying to reach(randomly generated); prevHeight:stores last value of height;delay in radomness;
public float radius = 40;
private void Start()
{
if (radius > 0)
{
var newPos = (transform.position - Turret.transform.position).normalized * radius;
newPos += Turret.transform.position;
transform.position = newPos;
}
}
// Update is called once per frame
void Update()
{
if (radius > 0)
{
var newPos = (transform.position - Turret.transform.position).normalized * radius;
newPos += Turret.transform.position;
transform.position = newPos;
}
//Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update
transform.RotateAround(Turret.transform.position, axis.normalized, angle);
time += Time.deltaTime;
//Sets value of 'height' randomly within 'upperLimit' & 'lowerLimit' after delay
if (time > delay)
{
prevHeight = height;
height = Random.Range(lowerLimit, upperLimit);
time = 0;
}
//Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition)
transform.position = new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z);
}
}
The problem is with this part:
if (radius > 0)
{
var newPos = (transform.position - Turret.transform.position).normalized * radius;
newPos += Turret.transform.position;
transform.position = newPos;
}
It's working fine in the Start when running the game and changing the radius before running the game.
The problem is in the Update this part is not working good. If I set the radius for example to 1 the object rotate almost above the other object but then if I change the radius to 10 or 40 or 55 or 100 it's not moving back to the bigger radius track it keep staying on the radius size 1.
The problem is that it's not moving to the bigger radius when changing to a bigger radius when the game is running.
Comment