I am making a top down shooter in Java and I need to be able to shoot in a line tangent to the mouse coordinates. In other words I need to be able to click my mouse and have a projectile spawn from my player, then move its position in a straight line in the direction of where I clicked. I have tried this already and I have failed miserably, and after looking into it for a while I haven't found a good answer. The code is pasted below, any ideas on what I'm doing wrong?  The mouse angle is calculated like this:  mouseAngle = (float) Math.toDegrees((float) Math.atan2(e.getY() - Player.getY(), e.getX() - Player.getX()));    VectorMath class   package vector;  public class VectorMath {      public VectorMath() {      }      public static void copyVector(Vector2f v1, Vector2f v2){         v1.setX(v2.getX());         v1.setY(v2.getY());     }      public static void printVector(Vector2f v){         System.out.println("x: " + v.getX() + " y: " + v.getY());     }  }    Projectile Class   package projectile;  import java.awt.Color; import java.awt.Graphics2D;  import player.Mouse; import player.Player; import vector.Vector2f; import vector.VectorMath;  public class Bullet {      private Vector2f pos = new Vector2f(0, 0);     private float x,y, xVel, yVel, moveSpeed = 0.1f, dX, dY;;     private float mouseAngle;      public Bullet(Vector2f pos) {         VectorMath.copyVector(this.pos, pos);         VectorMath.printVector(this.pos);         x = Player.getX();         y = Player.getY();         mouseAngle = Mouse.getMouseAngle();     }      public void update(){         xVel = pos.getX() + (((float)Math.cos(mouseAngle)) / moveSpeed);         yVel = pos.getY() + (((float)Math.sin(mouseAngle)) / moveSpeed);          dX = x + xVel;         dY = y + yVel;          x = dX;         y = dY;      }      public void render(Graphics2D g2){         g2.setColor(Color.green);         g2.fillRect((int)x, (int)y, 10, 10);     }  }
52439
I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion).  I want the target to rotate and be facing right at the player.  The target, when it shoots something should shoot right at the player.    I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100%, and as long as it actually worked.  FYI - Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out.  Code samples run in the Target's class, Position = the targets position, Avatar = the player.  EDIT  Im now using Maik's c# code he has provided and it works great!
41459
How can I calculate the position of an object after "firing" it from a fixed point?  I am to create a small game - most likely with canvas (pure HTML, JS based) or Adobe Flash - in which the player fires objects at other obstacles in order to clear them.
112074
I'm making a top-down space shooter where the player controls a ship and can aim and shoot using the mouse cursor. How can I fire bullets from the ship at the angle from the ship to the mouse cursor?
108419
I'm building an MMO using Node.js, and there are monsters roaming around. I can make them move around on the server using vector variables acceleration, velocity and position.  acceleration = steeringForce / mass;  velocity += acceleration * dTime;  position += velocity * dTime;  Right now I just send the positions over, and tell the players these are the "target positions" of the monsters, and let the monsters move towards the target positions on the client with a speed dependant on the distance of the target position. It works but looks rather strange.  How do I synchronise these properly with the players without looking funny to them, taking into account the server lag?  The problem is that I don't know how to make use of the correct acceleration/velocity values here; right now they just move directly in a straight line to the target position instead of accelerating/braking there properly. How can I implement such behaviour?
53307
I'm trying to speed up my workflow by making vector points move in the opposite direction simultaneously when I have two highlighted. For instance, below I highlight the top and bottom of the arrow so they will move at the same time, except I want the bottom point to come up when I'm moving the top point down. Right now, they just move up together or down together. So if point 1 is at Y:20 and point 2 is at Y:10, I want them both to go to Y:15 if I move point 1 down 5 pixels.    What it currently does    What I want it to do
55203
I'm trying to make the joint rotate smoothly around the center of the canvas, toward the angle of mouse pointer. What I have works, but I want it to animate the shortest distance possible to get to the mouse angle. The problem occurs when the value loops around at the horizontal line (3.14 and -3.14). Mouseover that area to see how the direction switches and it takes the long way back around.  Relevant Code   // ease the current angle to the target angle joint.angle += ( joint.targetAngle - joint.angle ) * 0.1;  // get angle from joint to mouse var dx = e.clientX - joint.x,     dy = e.clientY - joint.y;   joint.targetAngle = Math.atan2( dy, dx );   How can I make it rotate the shortest distance, even "across the gap"?
59699
Here is the code.  \documentclass{article} \begin{document} \directlua{tex.sprint(tostring(math.sin(math.pi)))} \\ \directlua{tex.sprint(tostring(math.tan(math.pi/2)))} \end{document}   I am expecting the answers as 0 and error . The code above gives some very small and big number. Can I get the expected answers by some modifications in code?
116816
I have an A* implementation that works in "top down" situations where gravity is not taken into account for pathfinding. But, I am looking to modify to work in a 2d platformer situation. I am using the Unity Engine in C# but any examples or even pseudocode would be really helpful. I have found a source so far but it haven't been that helpful as I am not understanding the way they have adapted A*, I have listed them below.    (Very specific to authors implementation and hard to understand)
31475
A 2D game called Deer Hunter has projectiles like this:    Are the projectiles 2D or 3D models? How could I implement something similar?
79472
Well I have a simple 2D game where all positions are defined by and X and Y coordinate.  There are objects moving at a constant velocity. And a turret fires a bullet at the X and Y coordinates of the object. By the time the bullet goes to the desired area, the object has already moved.  So i need to adjust the X and Y target positions for the turret to shoot at taking into account the bullet speed and object speed.  Here's an image showing the problem.
110146
Based on this question:  I got some nice tools for illustrating to my students how to find the product of a number or a variable and a parenthesis.   However, the solution fails when I should have two sources in one line, for instance when expanding (a+3)(b+4). I would also be able to place a small number next to or above the arrowhead to indicate the first calculation, the second, etc. The second set of arrows could just as well go below the expression, not above it, to simplify things.   I could of course define myself a new set of macros similar to the existing ones, for instance \sourceTwo and \targetTwo, but it feels like this could be done more elegant.   MWE:  \documentclass[]{article} \usepackage[utf8]{inputenc} \usepackage{tikz}  \newcommand\source[1]{%     \tikz[remember picture,baseline,inner sep=0pt] {%         \node [name=source,anchor=base]{$#1$};     }%     \setcounter{target}{0} } \newcounter{target} \newcommand\target[1]{%     \tikz[remember picture,baseline,inner sep=0pt] {%         \node [name=target-\thetarget,anchor=base]{$#1$};     }%     \stepcounter{target}% } \newcommand\drawarrows{     \tikz[remember picture, overlay, bend left=45, -latex] {         \foreach \i [evaluate=\i as \n using int(\i-1)] in {1,...,\thetarget} {             \draw (source.north) to (target-\n.north);         }     } }  \begin{document}  \begin{equation}     (\source{a}+4)(\target{b}+\target{3}) = \drawarrows \end{equation}  \end{document}
62141
Here is my player code.  Rigidbody rb;  Vector3 currMovement; public float jumpSpeed = 10; public float moveSpeed = 10; public float rotSpeed = 180;  float distToGround;  public float posSmoothTime = 0.5f; float currPos; float targetPos; float posVel;  public float rotSmoothTime = 0.5f; float currRot; float targetRot; float rotVel;  void Start() {     rb = GetComponent&lt;Rigidbody&gt;();     distToGround = GetComponent&lt;Collider&gt;().bounds.extents.y; }  bool isGrounded() { return Physics.Raycast(transform.position, Vector3.down, distToGround + 0.1f); }  void Update() {     Move(); }  void Move() {     // Rotation smoothing.     targetRot = Input.GetAxisRaw("Horizontal") * rotSpeed * Time.smoothDeltaTime;      if (targetRot &gt; 360)         targetRot -= 360;     if (targetRot &lt; 0)         targetRot += 360;     currRot = Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, rotSmoothTime * Time.smoothDeltaTime);      transform.eulerAngles += new Vector3(0, currRot, 0);      // Movement smoothing.     targetPos = Input.GetAxisRaw("Vertical") * moveSpeed;      currPos = Mathf.SmoothDamp(currPos, targetPos, ref posVel, posSmoothTime * Time.smoothDeltaTime);     currMovement = new Vector3(0, 0, currPos);     currMovement = transform.rotation * currMovement;      if (isGrounded())     {         if (Input.GetButtonDown("Jump"))             rb.velocity += Vector3.up * jumpSpeed;     }      rb.position += currMovement * Time.smoothDeltaTime; }   I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script.  public Transform player; Quaternion targetLook; Vector3 targetMove; public float smoothLook = 0.5f; public float smoothMove = 0.5f; public float distFromPlayer = 5, heightFromPlayer = 3; Vector3 moveVel;  void LateUpdate() {     CameraMove(); }  void CameraMove() {     targetMove = player.position + (player.rotation * new Vector3(0, heightFromPlayer, -distFromPlayer));     transform.position = Vector3.SmoothDamp(transform.position, targetMove, ref moveVel, smoothMove);      targetLook = Quaternion.LookRotation(player.position - transform.position);     transform.rotation = Quaternion.Slerp(transform.rotation, targetLook, smoothLook); }   }  The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.
118519
I would like a button in my gui menu to follow a specific path if we selected it, I am wondering how I could do it: if we touch the button, then it can only move on the specific path, it is an arc such as this path :    Would you know how to achieve this? I am using Unity, but I think the theory should be the same for other software/language ?  Thanks for your help  __  EDIT:  here is the code for the bezier curve in unity : Where should I put the script?  using UnityEngine; using System.Collections;  public class DrawBezierHandle extends Editor {      public Transform startT;     public Transform endT;      function Start(){         startT = GameObject.Find("start").GetComponent("Transform") as Transform;         endT = GameObject.Find("end").GetComponent("Transform") as Transform;     }      function OnSceneGUI() {          var width : float = HandleUtility.GetHandleSize(Vector3.zero) * 0.1;         Handles.DrawBezier(startT.position,                          endT.position,                          startT.position * 5 * Vector.up,                          endT.position * 5 * Vector.up,                         Color.red,                          null,                         width);     } }
106425
After reading , I was playing around to make a command to create a TikZ command with two inputs like this:  \documentclass[10pt,a4paper]{article}  \usepackage{tikz} \usetikzlibrary{calc}  \begin{document} \centering  \newcommand{\mitsubishi}[2]{ % #1 = radius % #2 = position x,y \pgfmathparse{2.966/7} \pgfmathparse{#1*\pgfmathresult}  \filldraw (#2) circle(#1 cm); % plate  \foreach \angle in {0,120,240}{ \filldraw[white,rotate=\angle] (#2)--++(60:\pgfmathresult)--++(120:\pgfmathresult)--++(-120:\pgfmathresult)--cycle; } }  \begin{tikzpicture} \mitsubishi{2}{0,0} \end{tikzpicture} \end{document}   but I have problems with the command \pgfmathresult inside the \filldraw command.  Why?
50897
I am writing a chess game using Java and Swing, And I wanted to get the tile position on which a mouse clicked. I searched through internet, but all of them were really off, and never accurate. When I clicked on a tile's first half, it said it was tile 1, but on the second half, it said it was tile 2, but it was still tile 1. So I was wondering, how can I do it? My tile size is (75, 75) This is the code I've written for tileX: Math.floor((double)evt.getX() / 75), and this is the code I've written for tileY: Math.floor((double)evt.getY() / 75). Code for drawing: ImageIcon l_winter = new ImageIcon(&quot;/Users/user/NetBeansProjects/chess/src/b/bibe/assets/winter/light.gif&quot;);         ImageIcon d_winter = new ImageIcon(&quot;/Users/user/NetBeansProjects/chess/src/b/bibe/assets/winter/dark.gif&quot;);         ImageIcon l_wood = new ImageIcon(&quot;/Users/user/NetBeansProjects/chess/src/b/bibe/assets/wood/light.png&quot;);         ImageIcon d_wood = new ImageIcon(&quot;/Users/user/NetBeansProjects/chess/src/b/bibe/assets/wood/dark.png&quot;);         String theme = th;         int color = 0;         for (int i = 0; i &lt; 600; i = i + 75) {             for (int j = 0; j &lt; 600; j = j + 75) {                 JLabel panel = new JLabel();                 panel.setText(null);                 panel.setSize(75, 75);                 if (color == 0) {                     if (theme.equals(&quot;wood&quot;)) {                         panel.setIcon(l_wood);                     } else if (theme.equals(&quot;winter&quot;)) {                         panel.setIcon(l_winter);                     } else {                         panel.setText(&quot;notexture&quot;);                     }                     //panel.setBackground(new Color(white[0], white[1], white[2]));                     color = 1;                 } else {                     if (theme.equals(&quot;wood&quot;)) {                         panel.setIcon(d_wood);                     } else if (theme.equals(&quot;winter&quot;)) {                         panel.setIcon(d_winter);                     } else {                         panel.setText(&quot;notexture&quot;);                     }                     //panel.setBackground(new Color(black[0], black[1], black[2]));                     color = 0;                 }                 panel.setLocation(j, i);                 getContentPane().add(panel);             }         if (color == 0) {             color = 1;         } else {                color = 0;             }         }
3115
I see questions come up quite often that have this underlying issue, but they're all caught up in the particulars of a given feature or tool. Here's an attempt to create a canonical answer we can refer users to when this comes up - with lots of animated examples! :)    Let's say we're making a first-person camera. The basic idea is it should yaw to look left &amp; right, and pitch to look up &amp; down. So we write a bit of code like this (using Unity as an example):  void Update() {     float speed = lookSpeed * Time.deltaTime;      // Yaw around the y axis using the player's horizontal input.             transform.Rotate(0f, Input.GetAxis("Horizontal") * speed, 0f);      // Pitch around the x axis using the player's vertical input.     transform.Rotate(-Input.GetAxis("Vertical") * speed,  0f, 0f); }   or maybe  // Construct a quaternion or a matrix representing incremental camera rotation. Quaternion rotation = Quaternion.Euler(                         -Input.GetAxis("Vertical") * speed,                          Input.GetAxis("Horizontal") * speed,                          0);  // Fold this change into the camera's current rotation. transform.rotation *= rotation;   And it mostly works, but over time the view starts to get crooked. The camera seems to be turning on its roll axis (z) even though we only told it to rotate on the x and y!    This can also happen if we're trying to manipulate an object in front of the camera - say it's a globe we want to turn to look around:    The same problem - after a while the North pole starts to wander away to the left or right. We're giving input on two axes but we're getting this confusing rotation on a third. And it happens whether we apply all our rotations around the object's local axes or the world's global axes.  In many engines you'll also see this in the inspector - rotate the object in the world, and suddenly numbers change on an axis we didn't even touch!    So, is this an engine bug? How do we tell the program we don't want it adding extra rotation?  Does it have something to do with Euler angles? Should I use Quaternions or Rotation Matrices or Basis Vectors instead?
22640
I have a script that works but it does not do what I want it to do. My script makes an object rotate on when another is clicked. However, I want the object to continuously rotate until I click on the other object again. Right now when I click it rotates just a bit and stops.  Here is my script:   public class Rotate : MonoBehaviour {     public float speed =50f;     public GameObject target;      public void OnMouseDown(){        target.transform.Rotate (new Vector3(0, Time.deltaTime, 0) * speed);     }  }   How can I make the object rotate continuously until I click it again?