This is the 7th day of my participation in Gwen Challenge

I’ve talked about how to set up a game scene, but how to make the characters move

In Oasis, in addition to built-in components, the Oasis engine also provides a powerful scripting system. Scripting system is the link between the capabilities of the engine and the game logic. Scripts are extended from the Script base class. Users can use it to extend the functions of the engine or write their own game logic code in the lifecycle hook functions provided by the Script component.

Component lifecycle functions

Oasis provides users with rich lifecycle callback functions. As long as users define specific callback functions, Oasis will automatically execute related scripts at specific times, and users do not need to invoke them manually. The lifecycle callback functions currently provided to users are as follows:

There are two common life cycles that are described here

OnAwake ()

OnAwake: called when the component is activated for the first time. This is where you can do some initialization, such as initializing some of the component’s states, adding event listeners, etc.

OnUPdata ()

Onupdata: a callback to the engine’s main loop, where updates are made to each frame, such as component movements. Since the callbacks here are per-frame, it is not recommended to create new objects here.

The sample

Let’s take that as an example, and walk through how to make the character move, step by step. Okay

Introducing Script components

import { Script } from 'oasis-engine'

Create a class called moveScript to inherit Script

class moveScript extends Script {onAwake () {} onUpdata () {}}Copy the code

This group will then be bound to the role’s entity

roleEntity.addComponent(moveScript)

Declare some parameters

class moveScript extends Script {
    // Cache a point in time
    static tempPos: Vector3 = new Vector3()
    // Used for the starting position of the character
    static startPos: Vector3 = new Vector3()

    // Total current movement time
    private_totalTime! :number
    // Move speed
    private_speed! :number
    // Jump time and height
    private_jumpTime! :number
    private_jumpHeight! :number
    // Direction judgment
    private_isRight! :boolean
    private_isLeft! :boolean
    private_isJump! :boolean
    // Move the distance
    private_moveX! :number
    private_moveY! :number
    // Screen range
    private_screenLeft! :number
    private_screenRight! :number
    
    // Lifecycle functionsOnAwake () {} onUpdata () {}}Copy the code

Initialize the parameters in onAwake ()

    onAwake () {
      // Initialize parameters
      this._totalTime = 0 // Total movement time, starting with 0
      this._speed = 30 // Set the movement speed, can be adjusted according to their own needs
      this._moveX = 0 // The movement in the X direction starts at 0
      this._moveY = 0 // The movement in the Y direction starts at 0
      this._jumpTime = 0 // The total jump time, initially 0
      this._jumpHeight = -4 // The maximum height of the jump can be adjusted as required
      moveScript.tempPos.setValue(0.0.0) // Initialize the location

      // Calculates the initial position of the role
      const roleX = groundTexture.height * scaleTimes * 5
      const roleY = canvasY - groundTexture.height * scaleTimes * 2 - (roleTexture.height * rolescale) / 2
      const rolepoint = new Vector3(roleX, roleY)
      const roleout = new Vector3()
      // Initialize the role position
      moveScript.startPos = cameramash.screenToWorldPoint(rolepoint, roleout)

      // Calculate the left side of the screen
      const screemLeft = new Vector3((roleTexture.height * rolescale) / 2.0)
      const leftout = new Vector3()
      cameramash.screenToWorldPoint(screemLeft, leftout)
      // Initializes the left border position of the screen
      this._screenLeft = leftout.x

      // Calculate the coordinates on the right side of the screen
      const screenRight = new Vector3(canvasX, 0)
      const rightout = new Vector3()
      cameramash.screenToWorldPoint(screenRight, rightout)
      // Initializes the right border position of the screen
      this._screenRight = rightout.x

      // Keyboard event listener
      window.addEventListener('keydown'.e= > {
        if (e.key === 'ArrowRight') {
            // Use.flipx to change the Sprite orientation to the right
          roleRenderer.flipX = false
          this._isRight = true
        }
        if (e.key === 'ArrowLeft') {
            // Use.flipx to change the Sprite orientation to the left
          roleRenderer.flipX = true
          this._isLeft = true
        }
        // Note that the key code of the space bar is not empty, it is space ' '.
        if (e.key === ' ') {
          this._isJump = true}})window.addEventListener('keyup'.e= > {
        if (e.key === 'ArrowRight') {
          this._isRight = false
        }
        if (e.key === 'ArrowLeft') {
          this._isLeft = false}})}Copy the code

Move in onUpdata ()

deltaTime

There is a deltaTime parameter in updata ()

Let’s see what deltaTime is first

onUpdate (deltaTime: number) :void {
      console.log(deltaTime)
    }
Copy the code

Is a number that fluctuates around 100, based on naive guesses, deltaTime is the number of frames. That is, Updata () will execute deltaTime this in 1 second, so we can get the time per frame 1 / deltaTime

So now that we have time and velocity, we can use the equation x = t*v that we learned in second grade to find the displacement

The theory is over. Here’s the code

    onUpdate (deltaTime: number) :void {
        // When the right button is pressed, the time increases,
        // Total time * speed to find the displacement distance
        // Use math.min () to make it as far to the right of the screen as possible
      if (this._isRight) {
        if(moveScript.tempPos.x ! = =this._screenRight) {
          this._totalTime += 1 / deltaTime
        }
        this._moveX = Math.min(this._totalTime * this._speed, -moveScript.startPos.x + this._screenRight)
      }
      
         // When the left key is pressed, the time is reduced plus,
        // Total time * speed to find the displacement distance
        // Use math.max () to make the left as far as the left side of the screen
      if (this._isLeft) {
        if(moveScript.tempPos.x ! = =this._screenLeft) {
          this._totalTime -= 1 / deltaTime
        }
        this._moveX = Math.max(this._totalTime * this._speed, -moveScript.startPos.x + this._screenLeft)
      }
      
        // Jump time increases when spacebar is pressed,
        // Total time * speed to find the displacement distance
        // The jump time decreases after the jump peaks
        // Total time * speed to find the displacement distance
        // Limit the lowest point with math.max ()
      if (this._isJump) {
        this._jumpTime += 1 / deltaTime
        this._moveY = this._jumpTime * this._speed
        if (moveScript.tempPos.y >= this._jumpHeight) {
          this._isJump = false}}else if (this._isJump === false && moveScript.tempPos.y > moveScript.startPos.y) {
        this._jumpTime -= 1 / deltaTime
        this._moveY = Math.max(this._jumpTime * this._speed, 0)}// Add startPos. X to the displacement this._moveX to get the value of tempPos
      moveScript.tempPos.x = moveScript.startPos.x + this._moveX
      // Add startPos. Y to the displacement this._movey to get the value of tempPos
      moveScript.tempPos.y = moveScript.startPos.y + this._moveY
      // Copy the temppos coordinates to use transform.position
      this.entity.transform.position = moveScript.tempPos
    }
Copy the code

end

You can see that you can now control the movement of the character. But when moving, there is no animation of the character moving. The next one will get him moving. Give a little like if you can

respect by myself