LocalPosition change affecting actual Position?
I have an enemy object that constantly follows the player using A*. I wanted to add a little shake to it for the feedback for an electric weapon to give the impression they were just "shocked." So I parented the SpriteRenderer to an empty transform with the Collider and RB. I added the "shake" script to the sprite object to affect it separately from the RB object.
Problem is, the script ends and I want to move the Sprite back to the Collider object's current position. So I assign the localPosition back to (0,0,0), but it instead transports the entire object (including the collider) back to the (0,0,0) of the scene, as if I had altered the actual Position instead.
The enemies are prefabs which for now are being instantiated via a wave spawner. Here's my code if someone can tell me what's up with this:
private float shakeAmount = 0f; private EnemyAI enemyAIClone; private Transform myRef; private Vector3 zero;
// Use myRef for initialization
void Awake()
{
enemyAIClone = GetComponentInParent<EnemyAI> ();
myRef = this.gameObject.GetComponentInChildren<Transform>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
//Test the shake
StunShake (0.3f, .3f, true);
}
}
public void StunShake (float _amnt, float _leng, bool _isExplosion)
{
if (IsInvoking ("BeginShake") == false || _isExplosion == true)
{
shakeAmount = _amnt;
zero = new Vector3(0,0,0);
InvokeRepeating ("BeginShake", 0.01f, .02f);
if(enemyAIClone.stun == false)
{
Invoke ("StopShake", _leng);
}
}
}
// Update is called once per frame
void BeginShake ()
{
if (shakeAmount > 0)
{
Vector3 myPos = myRef.position;
if (Vector3.Distance(myPos, myRef.position) <= shakeAmount/30)
{
myPos = myRef.position + Random.insideUnitSphere * shakeAmount;
}
myRef.position = Vector3.Lerp(myRef.position, myPos , 1f);
//myRef.transform.localPosition = Vector3.Lerp(myPos, Vector3.zero , 1f);
}
}
void StopShake ()
{
CancelInvoke ("BeginShake");
zero = myRef.GetComponentInParent<Transform>().position;
myRef.position = Vector3.Lerp(myRef.position, zero , 1f);
myRef.localPosition = new Vector3 (0, 0, 0);
}
Answer by NoseKills · Mar 08, 2016 at 03:37 PM
Did you check what GetComponentInChildren() returns?
Based on that (without reading all of the code I admit), to me it looks like your 'myRef' is probably the transform of the parent, the one that you don't want to reset to 0,0,0 but now you do.
Another oddity i see is
myRef.position = Vector3.Lerp(myRef.position, zero , 1f);
That's exactly the same as
myRef.position = zero;
You should check the api docs for what Lerp does also :)