- Home /
How to set a target position in Vector3.MoveTowards using a variable
so i want a target position for my camera to move to be -10 away from the current x position of an object. I got this and got stuck.
function moveCamera () {
var myVar : double;
myVar= GameObject.Find("First Person Controller").transform.position.x;
myVar-= 10;
transform.position = Vector3.MoveTowards(transform.position, myVar, .05);
}
The Consoles says that I cannot use myVar in the MoveTowards because it uses a Vector3 but then i cannot subtract the 10 from myVar if it is a vector3.
Thank you in advance.
Answer by voporak5 · Jul 08, 2015 at 03:52 PM
change myVar to Vector3
and also do this
function moveCamera () {
var myVar : Vector3;
myVar= GameObject.Find("First Person Controller").transform.position;
var myTarg = myVar.x -= 10;
myVar = Vector3(myTarg, myVar.y, myVar.z);
transform.position = Vector3.MoveTowards(transform.position, myVar, .05);
}
I do mostly C# so I think that's it, I'm not 100% if the syntax is correct.
line four the -= should just be a - but everything else worked
Answer by kjakubison · Jul 08, 2015 at 04:30 PM
The method MoveTowards expects a Vector3 and not a double which is why you are having issues. Here is a link to the reference for MoveTowards in JS.
http://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
I didn't test this but the following should fix your issue.
function moveCamera () {
var originalPos : Vector3;
var targetPos : Vector3;
originalPos = GameObject.Find("First Person Controller").transform.position;
targetPos = Vector3(originalPos.x, originalPos.y - 10,originalPos.z);
transform.position = Vector3.MoveTowards(transform.position, targetPos, .05);
}
**As a side note. You may experience issues if this is not being used in an Update function as it will only move once instead of every frame.
you don't have to worry the moveCamera function will have a for loop in it