Это заготовка для собственной библиотеки линейной алгебры.
*/
public class Vector2f extends AbstractVector {
private static final int SIZE = 2;
private float[] components = new float[SIZE];
private float length;
/**
- Конструктор для создания вектора с заданными компонентами.
- @param x Компонента по оси X.
- @param y Компонента по оси Y.
*/
public Vector2f(float x, float y) {
this.components[0] = x;
this.components[1] = y;
calcLength();
}
/**
- Конструктор для создания нулевого вектора.
*/
public Vector2f() {
this.components[0] = 0;
this.components[1] = 0;
calcLength();
}
// Геттеры и сеттеры для компонентов X и Y
public float getX() {
return components[0];
}
public void setX(float x) {
components[0] = x;
calcLength();
}
public float getY() {
return components[1];
}
public void setY(float y) {
components[1] = y;
calcLength();
}
/**
- Возвращает компонент вектора по индексу.
- @param index Индекс компонента (0 для X, 1 для Y).
- @return Значение компонента.
- @throws IndexOutOfBoundsException если индекс не равен 0 или 1.
*/
public float getNum(int index) {
if (index < 0 || index >= components.length) {
throw new IndexOutOfBoundsException("Неверный индекс: " + index);
}
return components[index];
}
/**
- Заменяет значение компонента вектора по индексу.
- @param index Индекс компонента (0 для X, 1 для Y).
- @param num Новое значение для компонента.
- @throws IndexOutOfBoundsException если индекс не равен 0 или 1.
*/
public void setNum(int index, float num) {
if (index < 0 || index >= components.length) {
throw new IndexOutOfBoundsException("Неверный индекс: " + index);
}
components[index] = num;
calcLength();
}
/**
- Вычисляет длину вектора и сохраняет её.
*/
private void calcLength() {
length = (float) Math.sqrt(components[0] * components[0] + components[1] * components[1]);
}
@Override
public float length() {
return length;
}
/**
- Нормализует вектор.
- Если длина вектора равна нулю, метод ничего не делает.
*/
private void calcNormalize() {
calcLength();
if (length == 0) {
return;
}
divide(length);
}
@Override
public void normalize() {
calcNormalize();
}
/**
- Складывает текущий вектор с другим вектором.
- @param other Другой вектор для сложения.
- @return Новый вектор, являющийся суммой двух векторов.
- @throws IllegalArgumentException если тип другого вектора не Vector2f.
*/
@Override
public Vector2f add(AbstractVector other) {
if (!isVector2f(other)) {
throw new IllegalArgumentException("Неверный тип вектора для сложения");
}
Vector2f o = (Vector2f) other;
return new Vector2f(
this.components[0] + o.components[0],
this.components[1] + o.components[1]
);
}
/**
- Вычитает из текущего вектора другой вектор.
- @param other Другой вектор для вычитания.
- @return Новый вектор, являющийся разностью двух векторов.
- @throws IllegalArgumentException если тип другого вектора не Vector2f.
*/
@Override
public Vector2f sub(AbstractVector other) {
if (!isVector2f(other)) {
throw new IllegalArgumentException("Неверный тип вектора для вычитания");
}
Vector2f o = (Vector2f) other;
return new Vector2f(
this.components[0] - o.components[0],
this.components[1] - o.components[1]
);
}
@Override
public void sub(AbstractVector other, AbstractVector second) {
if (!(isVector2f(other) && isVector2f(second))) {
new Exception("не правильный тип векторов");
}
Vector2f o = (Vector2f) other;
Vector2f s = (Vector2f) second;
this.components[0] = o.getX() - s.getX();
this.components[1] = o.getY() - s.getY();
}
/**
- Умножает текущий вектор на скаляр.
- @param scalar Скаляр для умножения.
*/
@Override
public void multiply(float scalar) {
for (int i = 0; i < components.length; i++) {
this.components[i] *= scalar;
}
calcLength();
}
/**
- Делит текущий вектор на скаляр.
- @param scalar Скаляр для деления.
- @throws ArithmeticException если скаляр равен нулю.
*/
@Override
public void divide(float scalar) {
if (scalar == 0) {
throw new ArithmeticException("Деление на ноль");
}
for (int i = 0; i < components.length; i++) {
this.components[i] /= scalar;
}
calcLength();
}
/**
- Вычисляет скалярное произведение текущего вектора с другим вектором.
- @param other Другой вектор для скалярного произведения.
- @return Значение скалярного произведения.
- @throws IllegalArgumentException если тип другого вектора не Vector2f.
*/
@Override
public float dot(AbstractVector other) {
if (!isVector2f(other)) {
throw new IllegalArgumentException("Неверный тип вектора для скалярного произведения");
}
Vector2f o = (Vector2f) other;
return this.components[0] * o.components[0] + this.components[1] * o.components[1];
}
/**
- Проверяет, является ли другой вектор экземпляром Vector2f.
- @param other Другой вектор для проверки.
- @return true если другой вектор является Vector2f, иначе false.
*/
private boolean isVector2f(AbstractVector other) {
return other instanceof Vector2f;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Vector2f)) return false;
Vector2f other = (Vector2f) obj;
return Float.compare(components[0], other.components[0]) == 0 &&
Float.compare(components[1], other.components[1]) == 0;
}
@Override
public int hashCode() {
return Objects.hash(components[0], components[1]);
}
@Override
public String toString() {
return "Vector2f{" +
"x=" + components[0] +
", y=" + components[1] +
'}';
}
}package com.cgvsu.math;