c# - How can I make this movement relative to my camera direction -
i need move target object in world space relative direction main camera facing on x&z axis , relative player on on y axis.
any guidance appreciated.
public class test : monobehaviour { public string raise = "raise"; public string lower = "lower"; public string left = "left"; public string right = "right"; public string closer = "closer"; public string further = "further"; public gameobject target; private float xpos; private float ypos; private float zpos; // use initialization void start () { xpos = target.transform.position.x; ypos = target.transform.position.y; zpos = target.transform.position.z; } void fixedupdate () { vector3 currpos = target.transform.position; vector3 nextpos = new vector3 (xpos, ypos, zpos); target.getcomponent < rigidbody > ().velocity = (nextpos - currpos) * 10; if (input.getbutton (raise)) { print ("moving up"); ypos = ypos + 0.05f; } if (input.getbutton (lower)) { print ("moving down"); ypos = ypos - 0.05f; } if (input.getbutton (left)) { print ("moving left"); xpos = xpos - 0.05f; } if (input.getbutton (right)) { print ("moving right"); xpos = xpos + 0.05f; } if (input.getbutton (closer)) { print ("moving closer"); zpos = zpos - 0.05f; } if (input.getbutton (further)) { print ("moving further"); zpos = zpos + 0.05f; } }
you can camera's direction this:
var camdir = camera.main.transform.forward;
you want x/y component, we're going renormalise vector:
camdir.y = 0; camdir.normalized();
that's forward vector. because it's 2d vector now, can cam's right-hand vector easily:
var camright = new vector3(camdir.z, 0f, -camdir.x);
i'm going assum player's direction y axis. if it's different, sub in vector:
var playerup = vector3.up;
now, in sample you're doing manual integration, passing off rigid body system integration again. let's work out our own velocity directly:
var newvel = vector3.zero; if (/*left*/) newvel -= camright * 0.05; if (/*right*/) newvel += camright * 0.05; if (/*closer*/) newvel -= camdir * 0.05; if (/*farter*/) newvel += camdir * 0.05; if (/*raise*/) newvel += playerup * 0.05; if (/*lower*/) newvel -= playerup * 0.05;
change 0.05 if want move faster or more slowly. can lots of stuff here make controls feel nice, having little deadzone or feeding directly off analogue input rather buttons.
then commit rigid body:
target.getcomponent<rigidbody>().velocity = newvel;
Comments
Post a Comment