Hi again Panda Forum!!!
I’m working on a “slow motion typing” function to display text in the screen like in almost every game with text dialogues between two or more character.
This is the code I have done so far:
from panda3d.core import TextNode
from direct.showbase.ShowBase import ShowBase
from direct.stdpy.file import *
from direct.task import Task
import direct.directbase.DirectStart
import sys
class texto(ShowBase):
def __init__(self):
self.c = 0
self.x = 0
self.bool = 1
# Setup a TextNode
self.text = TextNode('node name')
self.text.ALeft
self.text.setWordwrap(25.0)
self.text.setText("Press space to load the text!")
# Get textNodePath to make some basic transformations
self.textNodePath = aspect2d.attachNewNode(self.text)
self.textNodePath.setScale(0.07)
self.textNodePath.setPos(-0.9, 0, -0.5)
# Open a text file for reading
self.textFile = open("text.txt")
self.lines = self.textFile.readlines()
# Close the file --IMPORTANT--
self.textFile.close()
# The method readlines() provide us with a list of lines from a specified file, but with null characters like "\n"
# Thats why we have to remove them manually with this function (defined bellow)
self.lines = self.nonull(self.lines)
# Accept the "escape" key to close the program
self.accept("escape", sys.exit)
self.accept("a", self.printLines)
self.accept("space", self.displayText, [self.text, self.lines])
# Just an auxiliar function for testing
def printLines(self):
print self.lines
print self.lines[0][4]
print len(self.lines[self.x])
# Function to remove the "\n"s from all lines
def nonull(self, lines):
return [line.replace("\n", "") for line in lines]
def displayText(self, textNode, lines):
if self.bool:
self.bool = 0
textNode.setText("")
taskMgr.add(self.sloMoText, "slow motion text")
def sloMoText(self, task):
# This sentece set the time between "typings"
if task.time < 0.05:
return task.cont
if self.c < len(self.lines[self.x]):
self.text.appendText(self.lines[self.x][self.c])
# Go to the next character in the line
self.c += 1
else:
self.c = 0
self.bool = 1
# Go to the next line in the file
if self.x < (len(self.lines)-1):
self.x += 1
else:
self.x = 0
return task.done
return task.again
texto = texto()
run()
Note that you need a text.txt in the same folder with several lines of text, and the function will read the lines in the file, store them in a list, and then print them in “slow motion” by pressing space.
My question here is: Is there a better way to do this??
I presume that yes
When this is enough “polished” I’ll post it in the snippet section.
Thanks in advance!!
EDIT: 1) Changed the title for a no misleading one!
2) Added a line to the code that close the file after reading it.