unity3d - Moving object from one postion to another in unity -
unity3d - Moving object from one postion to another in unity -
i have code here ,i trying move object 1 position ,on mouse click ,but everytime run it justs instantiate projectile object in specific position while had instantiate in ffor object position
using unityengine; using system.collections; public class shoot : monobehaviour { public gameobject projectile; public gameobject foot; public gameobject mouse; void start() { } void update() { if (input.getmousebuttondown(0)) { vector2 target = input.mouseposition; vector2 pos1 = camera.main.screentoworldpoint(target); gameobject newobj = (gameobject)gameobject.instantiate(projectile); vector2 pos2 = foot.transform.position; transform.position=vector2.lerp(pos2,pos1,time.deltatime); } }
there several issues here, i'll address them 1 @ time. first, code moving projectile wired wrong:
transform.position=vector2.lerp(pos2,pos1,time.deltatime);
you moving object "shoot" attached to, not new game object (newobj, have named it.)
second, it's of import understand update pattern , how utilize it. update run every frame. time.deltatime how much time has passed between lastly frame render , one. number small. lastly, input.getmousebuttondown true on first frame mouse pressed.
the current code have attempts (but fails, due other code problems) move projectile 1 frame mouse clicked. want mouse click spawn projectile, , projectile move forwards every update.
this best accomplished 2 classes. phone call them gun , seekerbullet. gun class responsible creating bullet every time mouse button pressed. seekerbullet class responsible moving bullet it's target.
gun
public seekerbullet projectileprefab; void update() { if (input.getmousebutton(0)) { vector2 target = camera.main.screentoworldpoint(input.mouseposition); firebullet(target); } } void firebullet(vector2 target) { gameobject projectile = (gameobject)gameobject.instantiate(projectileprefab, transform.position, quaternion.identity); projectile.getcomponent<seekerbullet>().target = target; }
seekerbullet
public float movespeed = 5; public vector2 target { get; set; } public void update() { transform.position = vector3.movetowards(transform.position, target, movespeed * time.deltatime); if (transform.position == target) onreachtarget(); } void onreachtarget() { // whatever want here destroy(gameobject); // delete seekerbullet }
the main thought i'm trying stress isolating code perform it's 1 function well. gun shouldn't responsible moving projectile, creating , telling go.
also, note projectile starting wherever gun is. see line
gameobject projectile = (gameobject)gameobject.instantiate(projectileprefab, transform.position, quaternion.identity);
the transform.position position of gun object. if want start @ foot, have in code, can re-implement have in example.
unity3d
Comments
Post a Comment