How to make a ray PHP

Learn how to generate random numbers in PHP with an easy-to-follow example.

Creating a Ray in PHP

A ray is a mathematical object that has a starting point and a specified direction, but has no length. In PHP, we can create a Ray class to represent rays. This class will have two properties: a starting point and a unit vector that represents the direction of the ray. We will also create methods to calculate the endpoint of the ray, the length of the ray, and the reflection of the ray.

To begin, we will define a Ray class. This class will accept two parameters: a starting point and a unit vector. The starting point should be an associative array containing the x and y coordinates of the starting point. The unit vector should be an associative array containing the x and y components of the vector.

class Ray {
  protected $start;
  protected $unit_vector;
  
  public function __construct($start, $unit_vector) {
    $this->start = $start;
    $this->unit_vector = $unit_vector;
  }
}

Next, we will create methods to calculate the endpoint of the ray, the length of the ray, and the reflection of the ray. We will also create a helper function, calculate_length(), that will calculate the length of a vector given its components.

protected function calculate_length($x, $y) {
  return sqrt(pow($x, 2) + pow($y, 2));
}

public function calculate_endpoint() {
  $x = $this->start['x'] + $this->unit_vector['x'];
  $y = $this->start['y'] + $this->unit_vector['y'];
  
  return array('x' => $x, 'y' => $y);
}

public function calculate_length() {
  $x = $this->unit_vector['x'];
  $y = $this->unit_vector['y'];
  
  return $this->calculate_length($x, $y);
}

public function calculate_reflection() {
  $x = -$this->unit_vector['x'];
  $y = -$this->unit_vector['y'];
  
  return array('x' => $x, 'y' => $y);
}

To finish, we will add a method to display the ray as a string. This method will take the starting point and the endpoint of the ray and format them as a string.

public function to_string() {
  $start_string = '(' . $this->start['x'] . ', ' . $this->start['y'] . ')';
  $endpoint = $this->calculate_endpoint();
  $endpoint_string = '(' . $endpoint['x'] . ', ' . $endpoint['y'] . ')';
  
  return $start_string . ' ---> ' . $endpoint_string;
}

We have now completed the Ray class. We can now create a ray and use the methods we have defined to calculate the endpoint, length, and reflection of the ray.

Answers (0)