- Home /
What's wrong with this code?
So basically I've got two objects box1 and box2 I've made box1 to move to the box2 (without accelerating or anything like that. just move and stop) but the problem is if I will turn box1 180, it will act weird, it will move around the map in circles until it reaches the box2 just like something goes in to the black hole... Here is the code:
var target : Transform;
var speed : float = 1;
function Update() {
transform.Translate((target.transform.position - transform.position).normalized * speed *Time.deltaTime);
}
So basically I want box1 to move straight to the box2 without making curves and stuff Also would be awesome if it will face to the box2, no matter how I will turn it. HELP PLEAAASAEEE????????!?!?!?!
I formated your code. Please use the 101010 button when you insert code into a post, so it is easier to read. Also 'help me' is not an useful tag.
Answer by Piflik · Aug 26, 2012 at 02:10 PM
Number1: target is already a transform, so target.transform.position is redundant. target.position is enough.
Number2: target.position - transform.position is a Vector3 in World Coordinates, whereas transform.Translate() uses local coordinates by default. This should work:
transform.Translate((target.position - transform.position).normalized * speed *Time.deltaTime, Space.World);
Thanks! I've got another question: I've added the collision detection (using trigger) and I want the box1 when it touches the target (box2) to change the target to the "box3" var target : Transform; var speed : float = 1; function Update() { transform.Translate((target.position - transform.position).normalized * speed *Time.deltaTime, Space.World); } function OnTriggerEnter (hit:Collider) { if(hit.gameObject.name == "target"){
Debug.Log("hit");
}
}
But I am not sure how do I change the variable...
I would use three variables: 1 to store box2, one to store box3 and the third as the target.
var target1 : Transform;
var target2 : Transform;
var target : Transform;
function Start() {
target = target1;
}
function OnTriggerEnter() {
target = target2;
}
If you have more than 2 targets, I would use an array to store all of them and then just change the index variable.
Answer by Dasherz · Aug 26, 2012 at 02:03 PM
Do u have rigid bodies on them?
To get them to look at each other look up the transform.LookAt() code it's pretty easy. try Turning off the rigidbodies. You only need it if u need them to collide or get effected by physics. You could also try turning off gravity and freezing constraints most likely the rotation.
Hope that helped
Your answer
Follow this Question
Related Questions
audio problems with my trigger script, help please 1 Answer
Does Unity Free download allow publishing online? 1 Answer
AppendProject error 2 Answers
Asset store 1 Answer