Log In  


Cart #print_sprite-2 | 2025-07-09 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA

A simple function for inserting sprites in the middle of text on screen.
There's a second version that can also highlight text. I made them different to reduce overhead if you only need the first one.

prtspr() arguments:

txtbl: text table, combo of strings and sprite numbers. Example: {"hello",5,"world"}
x,y: line position
c: text color
spry: adjust sprite y pos (optional argument)

prtspr_2() arguments:

txtbl: text table, combo of strings and sprite numbers. Example: {"hello",5,"world"}
x,y: line position
ct: text color
ch: highlight color
spry: adjust sprite y pos (optional argument)

the code

function prtspr(txtbl,x,y,c,spry)
	local lx=x --current x on line
	for t in all(txtbl) do
		if tonum(t) == nil then
			--is text
			print(t,lx,y,c)
			local len=#t
			lx += (len)*4
		else
			--is sprite number
			local sy = y-1
			if (spry) sy+=spry
			spr(t,lx,sy)
			lx += 9
		end
	end
end

A more complex version of the function with text highlight if string start with a special char like ^. The highlight character is removed when printing the string

function prtspr_2(txtbl,x,y,ctx,chi,spry)
	local lx=x --current x on line
	for t in all(txtbl) do
		if tonum(t) == nil then
			--is text
			--check for starting ^ to highlight
			local col = ctx
			local len=#t
			if sub(t,1,1) == "^" then
				len-=1
				print(sub(t,2),lx,y,chi)
			else
				print(t,lx,y,col)
			end
			lx += (len)*4
		else
			--is sprite number
			local sy = y-1
			if (spry) sy+=spry
			spr(t,lx,sy)
			lx += 9
		end
	end
end

Example use

function _draw()
	cls()

	--single sprite insertion between strings
	prtspr({"hello",4,"world"},30,40,12)

	--centering the sprite between two lines using the sprite y offset argument
	prtspr({3,"did you know you can\nput sprites in text?"},8,55,8,3)

	--multiple strings and sprites
	prtspr({"just ",1," like ",2," this"},17,75,8,-1)

	--alternate highlight function
	prtspr_2({"you got a ","^jelpi ",5,"!"},17,85,8,14,-1)
end



[Please log in to post a comment]