Cameras within the boundary of an A-frame restricted by distance

I'm trying to implement a code that restricts the camera movement in A-frame. The current functionality teleports the camera back to the position 0, 1.6, 0 when it moves 10 spaces away from the starting point on the x or y axis. However, I want to modify it so that the camera is only teleported back if its y position moves 10 spaces from the starting point. How can I achieve this? Here's the code snippet:

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
  <meta charset="UTF-8" />
</head>

<body>
  <script>
    AFRAME.registerComponent('limit-my-distance', {
      init: function() {
        this.zero = new THREE.Vector3(0, 0, 0);
      },
      tick: function() {
        if (this.el.object3D.position.distanceTo(this.zero) > 10) {
          this.el.object3D.position.set(0, 1.6, 0);
        }
      }
    });
  </script>
  <a-scene>
    <a-sphere position="0 2 -10"color="red"></a-sphere>
    <a-plane color="green" position="0 0 -5" rotation="-90 0 0" width="20" height="20"></a-plane>
    <a-camera limit-my-distance></a-camera>
    <a-sky color="#fff"></a-sky>
  </a-scene>
</body>

</html> 

Answer №1

Here's a neat trick to avoid getting stuck in walls when you're at position 4. You can also change the camera movement settings to use the WASD keys.

<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<script>
    AFRAME.registerComponent('limit-my-distance', {
      init: function() {
          // no code here
      },
      tick: function() {
        // limit Z position
        if (this.el.object3D.position.z > 3.8) {
          this.el.object3D.position.z = 3.8;
        }
        if (this.el.object3D.position.z < -3.8) {
          this.el.object3D.position.z = -3.8;
        }

        // limit X position
        if (this.el.object3D.position.x > 3.8) {
          this.el.object3D.position.x = 3.8;
        }
        if (this.el.object3D.position.x < -3.8) {
          this.el.object3D.position.x = -3.8;
        }

      }
    });
</script>
<a-scene>
<a-sphere position="0 2 -10"color="red"></a-sphere>
<a-plane color="green" position="0 0 -5" rotation="-90 0 0" width="20" height="20"></a-plane>
<a-camera limit-my-distance look-controls wasd-controls="acceleration:10" position="0 1.6 0"></a-camera>
<a-sky color="#fff"></a-sky>
</a-scene>

Answer №2

To specifically focus on the y axis, you can easily check the difference between two y-values:

// distance = |y_position - y_start|
const y = this.el.object3D.position.y;
const distance = Math.abs(0 - y);
if (distance > 10) {// perform your desired actions}

Here's an example showcasing this concept within an A-Frame environment:

<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent('limit-my-distance', {
    tick: function() {
      if (Math.abs(this.el.object3D.position.y) > 3) {
        this.el.object3D.position.y = 2;
      }
    }
  });
  AFRAME.registerComponent("fall", {
    tick: function() {
      this.el.object3D.position.y -= 0.15
    }
  })
</script>
<a-scene>
  <a-sphere position="0  2 -5" color="red" fall limit-my-distance></a-sphere>
  <a-plane color="green" position="0 0 -5" rotation="-90 0 0" width="20" height="20" material="wireframe: true"></a-plane>
  <a-camera></a-camera>
</a-scene>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Express.js: Implementing a Route that is Outside the Current Router

app.js: var app = express(); app.use('/my-page', require('./routes/my-page.js')); my-page.js: const router = require('express').Router(); router.get('/one', function (req, res, next) { return res.send('thi ...

PugJS is failing to properly interpolate numbers from the JSON file

My goal is to display a list of interfaces retrieved from my router API, which is in JSON format. However, when using Pug, only the strings are being rendered and not the numbers. Here is the output (it displays correctly in HTML): em1 192.168.0.0/24 Addr ...

Accept only numerical values, addition and subtraction symbols, commas, the F5 key, and various other characters

I want to restrict key strokes to only numbers (including those on the numpad), minus (-) and plus (+) signs, and commas (,). Currently, it types twice when I input a number (e.g. 2 is displayed as 22) and replaces the current value with the new number. F ...

Creating unique sizes for each quad in Three.js using InstancedBufferGeometry and ShaderMaterial

I'm working on creating a visually dynamic scene filled with points of varying widths and heights. The challenge I'm facing is figuring out how to manipulate the vertices in the vertex shader to achieve customized sizes for each point. Here' ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

Is it possible to link a JavaScript object to a dropdown Select Option?

As I work on populating a select list with options using Javascript, I am looking for a way to attach a corresponding Javascript object to each option that can be easily accessed during the change event. While formulating this question, I began thinking a ...

Flex items maintaining their size when the window decreases

My goal is to arrange two plotly plots side by side within a CSS flexbox, with the ability to resize them as the window size changes. The issue I'm facing is that while the plots expand correctly when the window is enlarged, they fail to shrink when t ...

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

Get Facebook to recognize and display link previews for websites using ajax technology

It is commonly known that when copying a link from an HTML website onto Facebook, the platform will attempt to fetch available images as previews for the link. But what happens when the content is dynamically generated, such as with JavaScript? In this c ...

Why is the ajax request in JQuery initiated before the code in beforeSend is fully executed?

I have encountered an issue with my code. I am trying to get a Reload.gif to start playing on my webpage before sending an ajax request to reload the data. However, the GIF only starts playing after the success function is called. Here is the timeline of e ...

Is there a Javascript library available that can generate calendar links for Google, Yahoo, Outlook, and iCal?

I recently came across a sleek and professional web page widget that includes links (for example, and meetup.com). Could someone assist me in finding the library responsible for creating these links? I explored the discussion on Need a service that build ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

Universal PM2 Configuration Settings in JSON Format

My current process involves initiating numerous Node.js processes using pm2. These processes are configured in a JSON file and started by executing pm2 start pm2.json Upon examining the JSON file provided below, it's evident that there is significan ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name ...

Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out? I'm trying to center an image, a message, and a passw ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

When using Webpack, there may be difficulties resolving relative path import of express static files

I am currently developing an Outlook add-in with an Express server running. To ensure compatibility with Outlook Desktop, I need to transpile JavaScript to ES5 using Webpack. Below is the simplified structure of my project: /public /javascripts ssoAu ...

Steps to forward a restricted user to a specific webpage

I am currently utilizing NextJs and am in the process of creating a redirecting function for users who have been banned or blocked from accessing the DB/session. My attempt at this involved: redirect.js, where I created a custom redirect function. impo ...