How to get touch position in simple script

I am trying to get the touch position in a script. I got the events to call when I touch the object (or when dragging after touching it)
Sadly the positions I am trying to read give NaN.

I am not sure how to get the position of a touch from this event. Any insights here?
The sample projects seem to abstract this a bit and the documentation on this event did not have any sample code

Base code:

// This is a component file. You can use this file to define a custom component for your project.
// This component will appear as a custom component in the editor.

import * as ecs from '@8thwall/ecs'  // This is how you access the ecs library.

ecs.registerComponent({
  name: 'Draggable',
  schema: {
    camera: ecs.eid,
    distanceToCamera: ecs.f32,
    followSpeed: ecs.f32,

    // Add data that can be configured on the component.
  },
  schemaDefaults: {
    distanceToCamera: 1,
    followSpeed: 50,
    // Add defaults for the schema fields.
  },
  data: {
    touchPositionX: ecs.f32,
    touchPositionY: ecs.f32,

    // Add data that cannot be configured outside of the component.
  },
  add: (world, component) => {
    // Init data
    const {eid, dataAttribute} = component

    // Set to middle screen
    component.data.touchPositionX = 0.5
    component.data.touchPositionY = 0.5

    const HandleTouchStart = (position) => {
      // Set state to dragging
      // Update position

      const data = dataAttribute.cursor(eid)
      data.touchPositionX = position.x
      data.touchPositionY = position.y
      console.log(data.touchPositionX)
    }

    const HandleTouchMove = (position) => {
      // Update position
      const data = dataAttribute.cursor(eid)
      data.touchPositionX = position.x
      data.touchPositionY = position.y
      console.log(data.touchPositionX)
    }

    const HandleTouchEnd = () => {
      // Set state to dynamic/idle
    }

    world.events.addListener(component.eid, ecs.input.SCREEN_TOUCH_START, HandleTouchStart)
    world.events.addListener(component.eid, ecs.input.SCREEN_TOUCH_MOVE, HandleTouchMove)
    world.events.addListener(component.eid, ecs.input.SCREEN_TOUCH_END, HandleTouchEnd)
  },```

If you console.log position you’ll see that the is the object you get back.

It’s not actually position, it’s an object returned from the event.

So the correct way to access the actual position in your case would be:

position.data.position

Got it!
That works good, thanks

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.