- Home /
TransformDirection using original transform
I'm working on a simple script that will create an object a couple meters in front of the character. For now I've been using a default sphere. I tried to do it using transform.TransformDirection, but it seems to always use the character's original position for the transform. No matter where the character moves, the sphere is always created in relation to where the character started at the beginning of the level, instead of where it is at the moment. Let me know if I'm missing anything.
Here's the code:
using UnityEngine; using System.Collections;
public class spawnPrefab: MonoBehaviour {
public Transform sphere; float lastCast = -10f; float castTime = .5f; void Start () {
}
void Update () { if(Input.GetButton("Fire1")){ if(Time.time - lastCast > castTime){ spawn(); lastCast = Time.time; } } }
void spawn(){ Transform currentPos = transform; float currentY = transform.position.y; Vector3 newPos = currentPos.TransformDirection( Vector3.forward*3); newPos.y = currentY; Instantiate(sphere, newPos, transform.rotation);
}
}
Answer by Jesse Anders · Sep 26, 2010 at 11:06 PM
Your code rotates the vector (0, 0, 3) according to the player's rotation, but the player's position is not considered at all. So, newPos will always be some vector (approximately) 3 units away from the origin.
Since it looks like you want to treat the input value as a point in this case, you'll probably want to use TransformPoint() instead.
Your answer
Follow this Question
Related Questions
Push the player forward C# 0 Answers
Updating rotation of client not working - strange error 0 Answers
Network Trasnform Interpolation Factor 2 Answers
Finding local position and clamping movement 2 Answers
Can you pass along something like transform.position.x or y? not the value but the VARIABLE? 2 Answers