c# - Bullet hits the object not in the center of the screen -


when player shoot, bullet fly center of screen. if player stay close object, bullet hits not in center, because flies gun on right side of screen. how can fix this?

 public rigidbody projectile;  public int speed = 50;  public transform startbulletposition;   void update()  {      if (input.getbuttondown("fire1"))      {          rigidbody clone;          clone = instantiate(projectile, startbulletposition.position, transform.rotation) rigidbody;          var centre = new vector3(0.5f, 0.5f, 0f);          var ray = camera.main.viewportpointtoray(centre);          clone.velocity = ray.direction * speed;      }  } 

enter image description here

public rigidbody projectile; public transform startbulletposition; public float speed; public float rotationspeed; public camera camera;  vector3 startingdirection;  void start() {      startingdirection = startbulletposition.transform.forward;  }  void update() {      if (input.getbuttondown("fire1")) {          raycasthit hit;         vector3 targetdirection;          if (physics.raycast(camera.main.transform.position, camera.transform.forward, out hit)){              targetdirection = hit.transform.position - startbulletposition.position;          } else {              targetdirection = startingdirection;         }          vector3 newdirection = vector3.rotatetowards( startbulletposition.transform.forward, targetdirection, rotationspeed * time.deltatime, 0.0f);         startbulletposition.transform.forward = newdirection;          rigidbody clone;         clone = instantiate(projectile, startbulletposition.position, startbulletposition.rotation) rigidbody;         clone.velocity = targetdirection * speed;      }  } 

i raycast camera position see can hit , rotate weapon direction. in example code. weapon point center view on camera raycast hits.

also can control max turnspeed public float. make nice weapon movement , not instantaneous jumps.

here docu links of used in snippet: https://docs.unity3d.com/scriptreference/raycasthit.html https://docs.unity3d.com/scriptreference/vector3.rotatetowards.html

if raycast misses, stored original direction of weapon used. (assuming startbulletposition transform of weapon...)

if want, can add maxdistance parameter physics.raycast call limit distance on behaviour active.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -