操纵杆死区计算

时间:2009-12-22 06:27:28

标签: java trigonometry

我的问题:给定x和y,我需要计算所需操纵杆偏转的x和y。

当没有操纵杆死区时这很简单 - 我只使用x和y而不进行操作。

当存在死区时,我希望x = 0为零,x =非零,作为该死区以外的第一个值。

方形死区很简单。在下面的代码中,x和y从-1到1(包括-1和1)。死区从0到1,包括在内。

float xDeflection = 0;
if (x > 0)
 xDeflection = (1 - deadzone) * x + deadzone;
else if (x < 0)
 xDeflection = (1 - deadzone) * x - deadzone;

float yDeflection = 0;
if (y > 0)
 yDeflection = (1 - deadzone) * y + deadzone;
else if (y < 0)
 yDeflection = (1 - deadzone) * y - deadzone;

圆形死区比较棘手。经过一番愚弄,我想出了这个:

float xDeflection = 0, yDeflection = 0;
if (x != 0 || y != 0) {
 float distRange = 1 - deadzone;
 float dist = distRange * (float)Math.sqrt(x * x + y * y) + deadzone;
 double angle = Math.atan2(x, y);
 xDeflection = dist * (float)Math.sin(angle);
 yDeflection = dist * (float)Math.cos(angle);
}

这是极端情况下操纵杆偏转的输出(死区= 0.25):

Non-square joystick deflection. http://n4te.com/temp/nonsquare.gif

如您所见,偏转不会延伸到角落。 IE,如果x = 1,y = 1则xDeflection和yDeflection都等于0.918。随着较大的死区,问题变得更加严重,使得上图中的绿线看起来越来越像圆圈。在deadzone = 1时,绿线是一个与死区匹配的圆圈。

我发现通过一个小的改变,我可以扩大绿线所代表的形状和-1到1之外的剪辑值:

if (x != 0 || y != 0) {
 float distRange = 1 - 0.71f * deadzone;
 float dist = distRange * (float)Math.sqrt(x * x + y * y) + deadzone;
 double angle = Math.atan2(x, y);
 xDeflection = dist * (float)Math.sin(angle);
 xDeflection = Math.min(1, Math.max(-1, xDeflection));
 yDeflection = dist * (float)Math.cos(angle);
 yDeflection = Math.min(1, Math.max(-1, yDeflection));
}

我从试验和错误中得出了常数0.71。这个数字使形状足够大,角落在实际角落的几个小数位内。出于学术原因,任何人都可以解释为什么0.71恰好是这样做的数字?

总的来说,我不确定我是否采取了正确的方法。有没有更好的方法来完成我需要的循环死区?

我已经编写了一个简单的基于Swing的程序来直观显示正在发生的事情:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DeadzoneTest extends JFrame {
 float xState, yState;
 float deadzone = 0.3f;
 int size = (int)(255 * deadzone);

 public DeadzoneTest () {
  super("DeadzoneTest");
  setDefaultCloseOperation(DISPOSE_ON_CLOSE);

  final CardLayout cardLayout = new CardLayout();
  final JPanel centerPanel = new JPanel(cardLayout);
  getContentPane().add(centerPanel, BorderLayout.CENTER);
  centerPanel.setPreferredSize(new Dimension(512, 512));

  Hashtable labels = new Hashtable();
  labels.put(-255, new JLabel("-1"));
  labels.put(-128, new JLabel("-0.5"));
  labels.put(0, new JLabel("0"));
  labels.put(128, new JLabel("0.5"));
  labels.put(255, new JLabel("1"));

  final JSlider ySlider = new JSlider(JSlider.VERTICAL, -256, 256, 0);
  getContentPane().add(ySlider, BorderLayout.EAST);
  ySlider.setInverted(true);
  ySlider.setLabelTable(labels);
  ySlider.setPaintLabels(true);
  ySlider.setMajorTickSpacing(32);
  ySlider.setSnapToTicks(true);
  ySlider.addChangeListener(new ChangeListener() {
   public void stateChanged (ChangeEvent event) {
    yState = ySlider.getValue() / 255f;
    centerPanel.repaint();
   }
  });

  final JSlider xSlider = new JSlider(JSlider.HORIZONTAL, -256, 256, 0);
  getContentPane().add(xSlider, BorderLayout.SOUTH);
  xSlider.setLabelTable(labels);
  xSlider.setPaintLabels(true);
  xSlider.setMajorTickSpacing(32);
  xSlider.setSnapToTicks(true);
  xSlider.addChangeListener(new ChangeListener() {
   public void stateChanged (ChangeEvent event) {
    xState = xSlider.getValue() / 255f;
    centerPanel.repaint();
   }
  });

  final JSlider deadzoneSlider = new JSlider(JSlider.VERTICAL, 0, 100, 33);
  getContentPane().add(deadzoneSlider, BorderLayout.WEST);
  deadzoneSlider.setInverted(true);
  deadzoneSlider.createStandardLabels(25);
  deadzoneSlider.setPaintLabels(true);
  deadzoneSlider.setMajorTickSpacing(25);
  deadzoneSlider.setSnapToTicks(true);
  deadzoneSlider.addChangeListener(new ChangeListener() {
   public void stateChanged (ChangeEvent event) {
    deadzone = deadzoneSlider.getValue() / 100f;
    size = (int)(255 * deadzone);
    centerPanel.repaint();
   }
  });

  final JComboBox combo = new JComboBox();
  combo.setModel(new DefaultComboBoxModel(new Object[] {"round", "square"}));
  getContentPane().add(combo, BorderLayout.NORTH);
  combo.addActionListener(new ActionListener() {
   public void actionPerformed (ActionEvent event) {
    cardLayout.show(centerPanel, (String)combo.getSelectedItem());
   }
  });

  centerPanel.add(new Panel() {
   public void toDeflection (Graphics g, float x, float y) {
    g.drawRect(256 - size, 256 - size, size * 2, size * 2);
    float xDeflection = 0;
    if (x > 0)
     xDeflection = (1 - deadzone) * x + deadzone;
    else if (x < 0) {
     xDeflection = (1 - deadzone) * x - deadzone;
    }
    float yDeflection = 0;
    if (y > 0)
     yDeflection = (1 - deadzone) * y + deadzone;
    else if (y < 0) {
     yDeflection = (1 - deadzone) * y - deadzone;
    }
    draw(g, xDeflection, yDeflection);
   }
  }, "square");

  centerPanel.add(new Panel() {
   public void toDeflection (Graphics g, float x, float y) {
    g.drawOval(256 - size, 256 - size, size * 2, size * 2);
    float xDeflection = 0, yDeflection = 0;
    if (x != 0 || y != 0) {
     float distRange = 1 - 0.71f * deadzone;
     float dist = distRange * (float)Math.sqrt(x * x + y * y) + deadzone;
     double angle = Math.atan2(x, y);
     xDeflection = dist * (float)Math.sin(angle);
     xDeflection = Math.min(1, Math.max(-1, xDeflection));
     yDeflection = dist * (float)Math.cos(angle);
     yDeflection = Math.min(1, Math.max(-1, yDeflection));
    }
    draw(g, xDeflection, yDeflection);
   }
  }, "round");

  cardLayout.show(centerPanel, (String)combo.getSelectedItem());
  pack();
  setLocationRelativeTo(null);
  setVisible(true);
 }

 private abstract class Panel extends JPanel {
  public void paintComponent (Graphics g) {
   g.setColor(Color.gray);
   g.fillRect(0, 0, getWidth(), getHeight());
   g.setColor(Color.white);
   g.fillRect(0, 0, 512, 512);

   g.setColor(Color.green);
   if (true) {
    // Draws all edge points.
    for (int i = -255; i < 256; i++)
     toDeflection(g, i / 255f, 1);
    for (int i = -255; i < 256; i++)
     toDeflection(g, i / 255f, -1);
    for (int i = -255; i < 256; i++)
     toDeflection(g, 1, i / 255f);
    for (int i = -255; i < 256; i++)
     toDeflection(g, -1, i / 255f);
   } else if (false) {
    // Draws all possible points (slow).
    for (int x = -255; x < 256; x++)
     for (int y = -255; y < 256; y++)
      toDeflection(g, x / 255f, y / 255f);
   }

   g.setColor(Color.red);
   toDeflection(g, xState, yState);
  }

  abstract public void toDeflection (Graphics g, float x, float y);

  public void draw (Graphics g, float xDeflection, float yDeflection) {
   int r = 5, d = r * 2;
   g.fillRect((int)(xDeflection * 256) + 256 - r, (int)(yDeflection * 256) + 256 - r, d, d);
  }
 }

 public static void main (String[] args) {
  new DeadzoneTest();
 }
}

3 个答案:

答案 0 :(得分:4)

如果你有一个圆形的死区,.71实际上是0.70710678或2的平方根的一半 根据毕达哥拉斯定理计算

答案 1 :(得分:3)

我试着稍微改变一下这个问题。正如我已经了解了您的要求,算法应该

  1. 如果操纵杆位置在死区之外,则返回x / y值
  2. 如果操纵杆(部分)在死区内,则返回0 / y,x / 0或0/0
  3. 假设操纵杆被向上推,但x在定义的水平死区内,你想要坐标(0,y)。

    因此,在第一步中,我将测试操纵杆坐标是否位于定义的死区内。对于圆形,它非常简单,您只需将x / y坐标转换为距离(Pythagoras)并检查该距离是否小于圆半径。

    如果它在外面,则返回(x / y)。如果它在里面,检查x以及值是否在它们的水平或垂直死区内。

    这是一个概述我的想法的草稿:

    private Point convertRawJoystickCoordinates(int x, int y, double deadzoneRadius) {
    
        Point result = new Point(x,y); // a class with just two members, int x and int y
        boolean isInDeadzone = testIfRawCoordinatesAreInDeadzone(x,y,radius);
        if (isInDeadzone) {
          result.setX(0);
          result.setY(0);
        } else {
          if (Math.abs((double) x) < deadzoneRadius) {
            result.setX(0);
          }
          if (Math.abs((double) y) < deadzoneRadius) {
            result.setY(0);
          }
        }
        return result;         
    }
    
    private testIfRawCoordinatesAreInDeadzone(int x, int y, double radius) {
      double distance = Math.sqrt((double)(x*x)+(double)(y*y));
      return distance < radius;
    }
    

    修改

    以上思路使用原始坐标,因此假设原始x值范围为[-255,255],半径为2,并将操纵杆设置为x值(-3,-2,-1,0,1, 2,3),它将产生序列(-3,0,0,0,0,0,3)。所以死区被消隐了,但是从0跳到3。如果这是不需要的,我们可以将非死区从([-256,-radius],[radius,256])“拉伸”到(标准化)范围([-1,0],[0,1])。

    所以我只需要对转换后的原始点进行标准化:

    private Point normalize(Point p, double radius) {
       double validRangeX = MAX_X - radius;
       double validRangeY = MAX_Y - radius;
       double x = (double) p.getX();
       double y = (double) p.getY();
    
       return new Point((x-r)/validXRange, (y-r)/validYRange);
    }
    

    简而言之:它将x轴和y轴的有效范围(范围减去死区半径)标准化为[-1,1],以便raw_x = radius转换为normalized_x = 0.

    (该方法应该适用于正值和负值。至少我希望它可以,我目前没有IDE或JDK可以测试;)

答案 2 :(得分:3)

这就是我一起扔的东西。它表现得有点奇怪,但在界限上它很好:

private Point2D.Float calculateDeflection(float x, float y) {
    Point2D.Float center = new Point2D.Float(0, 0);
    Point2D.Float joyPoint = new Point2D.Float(x, y);
    Double angleRad = Math.atan2(y, x);

    float maxDist = getMaxDist(joyPoint);

    float factor = (maxDist - deadzone) / maxDist;

    Point2D.Float factoredPoint = new Point2D.Float(x * factor, y * factor);

    float factoredDist = (float) center.distance(factoredPoint);

    float finalDist = factoredDist + deadzone;

    float finalX = finalDist * (float) Math.cos(angleRad);
    float finalY = finalDist * (float) Math.sin(angleRad);

    Point2D.Float finalPoint = new Point2D.Float(finalX, finalY);

    return finalPoint;
}

编辑:错过了这个。

private float getMaxDist(Point2D.Float point) {
    float xMax;
    float yMax;
    if (Math.abs(point.x) > Math.abs(point.y)) {
        xMax = Math.signum(point.x);
        yMax = point.y * point.x / xMax;
    } else {
        yMax = Math.signum(point.y);
        xMax = point.x * point.y / yMax;
    }
    Point2D.Float maxPoint = new Point2D.Float(xMax, yMax);
    Point2D.Float center = new Point2D.Float(0, 0);
    return (float) center.distance(maxPoint);
}

它保留角度,但是缩放从0到边界之间到死区和边界之间的距离。最大距离变化,因为它的边是1,角的是sqrt(2),所以必须相应地改变比例。