No usage notes found

Who can help me explain what functions are implemented in the following usage. Isn’t sety the only way to set coordinates in the Y direction? Why do the coordinates of X, y and Z change after setting according to this method?,-25*dt)

Could you share a longer excerpt of your code? It would be guesswork to answer your question, without seeing, what actually is. Actor? Model? What is its parent? etc…

Just a theory, but it could be possible, that you changed the orientation of and getting the position of it relative to its parent node (presumably self.render), resulting in change in potentially all 3 axes.

To illustrate this with a short code example:

>>> r = NodePath('r')
>>> a = r.attach_new_node('a')
>>> a.set_h(45)
>>> a.set_y(a, -5)
>>> a.get_pos(r)
LPoint3f(3.53553, -3.53553, 0)

Not sure if that is what you are encountering, but without more detail about your specific test case, this would be my best guess.

I daresay that @tcdude is correct: You’re positioning the actor relative to itself (as a result of passing the actor in as the first parameter to “setY”). This means that you’re positioning it along its own, personal y-axis; if it’s at all rotated relative to its parent, then its personal y-axis will not necessarily match the y-axis of its parent.

If you were to leave out the first parameter, then you would be positioning the actor relative to its parent, and thus along that parent’s y-axis, I believe.

(Although note that, if the actor’s parent itself has a parent, and if the actor’s parent is rotated relative to its parent, then the actor’s y-axis will presumably still not match that of the actor’s parent’s parent, as the actor’s parent’s y-axis wouldn’t match the y-axis of the actor’s parent’s parent.)

Technically, actor.setY(actor, 25) does not affect the value of actor.getX(actor), which will always be 0. In fact, it does not even affect the value of actor.getY(actor), which is also always 0.

You’re setting it relative to its own coordinate system, which is not the same coordinate system that you get when you call getX/setY without an argument.

Well, thank you very much for your reply, but I’m sorry that I don’t have a real case. I’m just looking at Ralph’s case and I don’t understand this method. My code is really just a substitute for an actor. For your reply, now I probably understand that it is to realize the repositioning of actors. But in this statement, there is only one parameter except the actor object itself. I am particularly confused about why it affects the position change of the actor in other directions, and why it only changes in two directions? Why doesn’t the Z direction change?

Will this method automatically convert this parameter to increment in two directions?

from direct.showbase.ShowBase import ShowBase
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from panda3d.core import Filename, AmbientLight, DirectionalLight
from panda3d.core import PandaNode, NodePath, Camera, TextNode
from panda3d.core import CollideMask
from direct.gui.OnscreenText import OnscreenText
from import Actor
import random
import sys
import os
import math

# Function to put instructions on the screen.
def addInstructions(pos, msg):
    return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), scale=.05,
                        shadow=(0, 0, 0, 1), parent=base.a2dTopLeft,
                        pos=(0.08, -pos - 0.04), align=TextNode.ALeft)

# Function to put title on the screen.
def addTitle(text):
    return OnscreenText(text=text, style=1, fg=(1, 1, 1, 1), scale=.07,
                        parent=base.a2dBottomRight, align=TextNode.ARight,
                        pos=(-0.1, 0.09), shadow=(0, 0, 0, 1))

class RoamingRalphDemo(ShowBase):
    def __init__(self):
        # Set up the window, camera, etc.

        # Set the background color to black, 0, 0, 1))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0}

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")

        # Set up the environment
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #    <Collide> { Polyset keep descend }
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                           {"run": "models/ralph-run",
                            "walk": "models/ralph-walk"})
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        self.disableMouse(), self.ralph.getY() + 10, 2)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundColNp =
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays

        Uncomment this line to show a visual representation of the
        collisions occuring

        Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))

    # Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        dt = globalClock.getDt()

        If the camera-left key is pressed, move camera left.
        If the camera-right key is pressed, move camera right.

        if self.keyMap["cam-left"]:
  , -20 * dt)
        if self.keyMap["cam-right"]:
  , +20 * dt)

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        if self.keyMap["left"]:
            self.ralph.setH(self.ralph.getH() + 300 * dt)
        if self.keyMap["right"]:
            self.ralph.setH(self.ralph.getH() - 300 * dt)
        if self.keyMap["forward"]:
            self.ralph.setY(self.ralph, -25 * dt)

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"]:
            if self.isMoving is False:
                self.isMoving = True
            if self.isMoving:
                self.ralph.pose("walk", 5)
                self.isMoving = False

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.ralph.getPos() -
        camdist = camvec.length()
        if camdist > 10.0:
   + camvec * (camdist - 10))
            camdist = 10.0
        if camdist < 5.0:
   - camvec * (5 - camdist))
            camdist = 5.0

        # Normally, we would have to call traverse() to check for collisions.
        # However, the class ShowBase that we inherit from has a task to do
        # this for us, if we assign a CollisionTraverser to self.cTrav.

        # Adjust ralph's Z coordinate.  If ralph's ray hit terrain,
        # update his Z. If it hit anything else, or didn't hit anything, put
        # him back where he was last frame.

        entries = list(self.ralphGroundHandler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())

        if len(entries) > 0 and entries[0].getIntoNode().getName() == "terrain":

        # Keep the camera at one foot above the terrain,
        # or two feet above ralph, whichever is greater.

        entries = list(self.camGroundHandler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())

        if len(entries) > 0 and entries[0].getIntoNode().getName() == "terrain":
  [0].getSurfacePoint(render).getZ() + 1.0)
        if < self.ralph.getZ() + 2.0:
   + 2.0)

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        return task.cont

demo = RoamingRalphDemo()

The above “pand3d” comes with the Ralph case, which I see in this case. What’s more, it doesn’t confuse me that there is no relationship between the rotation angle and the moving direction, so how do actors move according to their angles when using this method?

In short, and roughly-speaking, each object has its own “perspective”, which may or may not match that of whatever it’s attached to.

When you call “setY” and provide an object in the first parameter, you’re essentially saying “move along the y-axis in the perspective of the object passed into the first parameter–that is, move in that object’s y-direction”. If that object’s perspective doesn’t match the perspective of the parent of the object that you’re moving, then the movement may not be along that parent’s y-axis.

Put it this way: Imagine that you’re standing in a room with x- and y- axes painted on the floor. Imagine also that you have x- and y- axes of your own, represented by rods attached to your clothes. Your y-axis rod would point directly forward from you, and your x-axis rod would point to your side.

Now, imagine that you turn a little, so that you’re not facing the room’s y-axis, and then step forward. Your rod-axes turned with you, so you’re still just stepping in your y-direction–but because you’ve turned, it’s also true that you’re stepping in both the room’s y-direction and its x-direction.

There’s a bit more information on how this works here (with illustrations):

I’m guessing that the object hasn’t been rotated so that it’s forward-axis points up or down relative to its parent. If it had been rotated that way, it would presumably have moved in the z-direction, too.

It should perhaps be noted that, depending on what you intend to have happen, you may be able to get the desired behaviour by leaving out the first parameter in “setY”, and instead getting the object’s y-position and adding your intended value to that. Like this: - 25*dt)
1 Like

Thank you very much. The explanation is very clear. I have understood!

1 Like

I’m glad! It’s my pleasure to have served. :slight_smile: