id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
117241
|
import {SchematicTestRunner} from '@angular-devkit/schematics/testing';
import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing';
import {COLLECTION_PATH} from '../../paths';
import {Schema} from './schema';
describe('material-table-schematic', () => {
let runner: SchematicTestRunner;
const baseOptions: Schema = {
name: 'foo',
project: 'material',
};
beforeEach(() => {
runner = new SchematicTestRunner('schematics', COLLECTION_PATH);
});
it('should create table files and add them to module', async () => {
const app = await createTestApp(runner, {standalone: false});
const tree = await runner.runSchematic('table', baseOptions, app);
const files = tree.files;
expect(files).toContain('/projects/material/src/app/foo/foo.component.css');
expect(files).toContain('/projects/material/src/app/foo/foo.component.html');
expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts');
expect(files).toContain('/projects/material/src/app/foo/foo.component.ts');
expect(files).toContain('/projects/material/src/app/foo/foo-datasource.ts');
const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts');
expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/);
expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m);
const datasourceContent = getFileContent(
tree,
'/projects/material/src/app/foo/foo-datasource.ts',
);
expect(datasourceContent).toContain('FooItem');
expect(datasourceContent).toContain('FooDataSource');
const componentContent = getFileContent(
tree,
'/projects/material/src/app/foo/foo.component.ts',
);
expect(componentContent).toContain('FooDataSource');
});
it('should add table imports to module', async () => {
const app = await createTestApp(runner, {standalone: false});
const tree = await runner.runSchematic('table', baseOptions, app);
const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts');
expect(moduleContent).toContain('MatTableModule');
expect(moduleContent).toContain('MatPaginatorModule');
expect(moduleContent).toContain('MatSortModule');
expect(moduleContent).toContain(`import { MatTableModule } from '@angular/material/table';`);
expect(moduleContent).toContain(`import { MatSortModule } from '@angular/material/sort';`);
expect(moduleContent).toContain(
`import { MatPaginatorModule } from '@angular/material/paginator';`,
);
});
it('should throw if no name has been specified', async () => {
const appTree = await createTestApp(runner);
await expectAsync(
runner.runSchematic('table', {project: 'material'}, appTree),
).toBeRejectedWithError(/required property 'name'/);
});
describe('standalone option', () => {
it('should generate a standalone component', async () => {
const app = await createTestApp(runner, {standalone: false});
const tree = await runner.runSchematic('table', {...baseOptions, standalone: true}, app);
const module = getFileContent(tree, '/projects/material/src/app/app.module.ts');
const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts');
const requiredModules = ['MatTableModule', 'MatPaginatorModule', 'MatSortModule'];
requiredModules.forEach(name => {
expect(module).withContext('Module should not import dependencies').not.toContain(name);
expect(component).withContext('Component should import dependencies').toContain(name);
});
expect(module).not.toContain('FooComponent');
expect(component).toContain('standalone: true');
expect(component).toContain('imports: [');
});
it('should infer the standalone option from the project structure', async () => {
const app = await createTestApp(runner, {standalone: true});
const tree = await runner.runSchematic('table', baseOptions, app);
const componentContent = getFileContent(
tree,
'/projects/material/src/app/foo/foo.component.ts',
);
expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false);
expect(componentContent).toContain('standalone: true');
expect(componentContent).toContain('imports: [');
});
});
describe('style option', () => {
it('should respect the option value', async () => {
const tree = await runner.runSchematic(
'table',
{style: 'scss', ...baseOptions},
await createTestApp(runner),
);
expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss');
});
it('should fall back to the @schematics/angular:component option value', async () => {
const tree = await runner.runSchematic(
'table',
baseOptions,
await createTestApp(runner, {style: 'less'}),
);
expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less');
});
});
describe('inlineStyle option', () => {
it('should respect the option value', async () => {
const tree = await runner.runSchematic(
'table',
{inlineStyle: true, ...baseOptions},
await createTestApp(runner),
);
expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css');
});
it('should fall back to the @schematics/angular:component option value', async () => {
const tree = await runner.runSchematic(
'table',
baseOptions,
await createTestApp(runner, {inlineStyle: true}),
);
expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css');
});
});
describe('inlineTemplate option', () => {
it('should respect the option value', async () => {
const tree = await runner.runSchematic(
'table',
{inlineTemplate: true, ...baseOptions},
await createTestApp(runner),
);
expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html');
});
it('should fall back to the @schematics/angular:component option value', async () => {
const tree = await runner.runSchematic(
'table',
baseOptions,
await createTestApp(runner, {inlineTemplate: true}),
);
expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html');
});
});
describe('skipTests option', () => {
it('should respect the option value', async () => {
const tree = await runner.runSchematic(
'table',
{skipTests: true, ...baseOptions},
await createTestApp(runner),
);
expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts');
});
it('should fall back to the @schematics/angular:component option value', async () => {
const tree = await runner.runSchematic(
'table',
baseOptions,
await createTestApp(runner, {skipTests: true}),
);
expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts');
});
});
});
| |
117246
|
import { AfterViewInit, Component, ViewChild<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%><% if(changeDetection !== 'Default') { %>, ChangeDetectionStrategy<% }%> } from '@angular/core';
import { <% if(standalone) { %>MatTableModule, <% } %>MatTable } from '@angular/material/table';
import { <% if(standalone) { %>MatPaginatorModule, <% } %>MatPaginator } from '@angular/material/paginator';
import { <% if(standalone) { %>MatSortModule, <% } %>MatSort } from '@angular/material/sort';
import { <%= classify(name) %>DataSource, <%= classify(name) %>Item } from './<%= dasherize(name) %>-datasource';
@Component({
selector: '<%= selector %>',<% if(inlineTemplate) { %>
template: `
<%= indentTextContent(resolvedFiles.template, 4) %>
`,<% } else { %>
templateUrl: './<%= dasherize(name) %>.component.html',<% } if(inlineStyle) { %>
styles: `
<%= indentTextContent(resolvedFiles.stylesheet, 4) %>
`<% } else { %>
styleUrl: './<%= dasherize(name) %>.component.<%= style %>'<% } %><% if(!!viewEncapsulation) { %>,
encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>,
changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %><% if(standalone) { %>,
standalone: true,
imports: [MatTableModule, MatPaginatorModule, MatSortModule]<% } %>
})
export class <%= classify(name) %>Component implements AfterViewInit {
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@ViewChild(MatTable) table!: MatTable<<%= classify(name) %>Item>;
dataSource = new <%= classify(name) %>DataSource();
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['id', 'name'];
ngAfterViewInit(): void {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
this.table.dataSource = this.dataSource;
}
}
| |
117247
|
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
// TODO: Replace this with your own data model type
export interface <%= classify(name) %>Item {
name: string;
id: number;
}
// TODO: replace this with real data from your application
const EXAMPLE_DATA: <%= classify(name) %>Item[] = [
{id: 1, name: 'Hydrogen'},
{id: 2, name: 'Helium'},
{id: 3, name: 'Lithium'},
{id: 4, name: 'Beryllium'},
{id: 5, name: 'Boron'},
{id: 6, name: 'Carbon'},
{id: 7, name: 'Nitrogen'},
{id: 8, name: 'Oxygen'},
{id: 9, name: 'Fluorine'},
{id: 10, name: 'Neon'},
{id: 11, name: 'Sodium'},
{id: 12, name: 'Magnesium'},
{id: 13, name: 'Aluminum'},
{id: 14, name: 'Silicon'},
{id: 15, name: 'Phosphorus'},
{id: 16, name: 'Sulfur'},
{id: 17, name: 'Chlorine'},
{id: 18, name: 'Argon'},
{id: 19, name: 'Potassium'},
{id: 20, name: 'Calcium'},
];
/**
* Data source for the <%= classify(name) %> view. This class should
* encapsulate all logic for fetching and manipulating the displayed data
* (including sorting, pagination, and filtering).
*/
export class <%= classify(name) %>DataSource extends DataSource<<%= classify(name) %>Item> {
data: <%= classify(name) %>Item[] = EXAMPLE_DATA;
paginator: MatPaginator | undefined;
sort: MatSort | undefined;
constructor() {
super();
}
/**
* Connect this data source to the table. The table will only update when
* the returned stream emits new items.
* @returns A stream of the items to be rendered.
*/
connect(): Observable<<%= classify(name) %>Item[]> {
if (this.paginator && this.sort) {
// Combine everything that affects the rendered data into one update
// stream for the data-table to consume.
return merge(observableOf(this.data), this.paginator.page, this.sort.sortChange)
.pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data ]));
}));
} else {
throw Error('Please set the paginator and sort on the data source before connecting.');
}
}
/**
* Called when the table is being destroyed. Use this function, to clean up
* any open connections or free any held resources that were set up during connect.
*/
disconnect(): void {}
/**
* Paginate the data (client-side). If you're using server-side pagination,
* this would be replaced by requesting the appropriate data from the server.
*/
private getPagedData(data: <%= classify(name) %>Item[]): <%= classify(name) %>Item[] {
if (this.paginator) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
} else {
return data;
}
}
/**
* Sort the data (client-side). If you're using server-side sorting,
* this would be replaced by requesting the appropriate data from the server.
*/
private getSortedData(data: <%= classify(name) %>Item[]): <%= classify(name) %>Item[] {
if (!this.sort || !this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort?.direction === 'asc';
switch (this.sort?.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'id': return compare(+a.id, +b.id, isAsc);
default: return 0;
}
});
}
}
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean): number {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
| |
117248
|
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {createTestApp} from '@angular/cdk/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import {compileString} from 'sass';
import * as path from 'path';
import {createLocalAngularPackageImporter} from '../../../../../tools/sass/local-sass-importer';
import {generateSCSSTheme} from './index';
import {Schema} from './schema';
// Note: For Windows compatibility, we need to resolve the directory paths through runfiles
// which are guaranteed to reside in the source tree.
const testDir = runfiles.resolvePackageRelative('../theme-color');
const packagesDir = path.join(runfiles.resolveWorkspaceRelative('src/cdk/_index.scss'), '../..');
const localPackageSassImporter = createLocalAngularPackageImporter(packagesDir);
describe('material-theme-color-schematic', () => {
let runner: SchematicTestRunner;
let testM3ThemePalette: Map<string, Map<number, string>>;
/** Transpiles given Sass content into CSS. */
function transpileTheme(content: string): string {
return compileString(
`
${content}
html {
@include mat.theme((
color: (
primary: $primary-palette,
tertiary: $tertiary-palette,
theme-type: light,
),
));
@if mixin-exists(high-contrast-overrides) {
& {
@include high-contrast-overrides(light);
}
}
&.dark-theme {
@include mat.theme((
color: (
primary: $primary-palette,
tertiary: $tertiary-palette,
theme-type: dark,
),
));
@if mixin-exists(high-contrast-overrides) {
& {
@include high-contrast-overrides(dark);
}
}
}
}
`,
{
loadPaths: [testDir],
importers: [localPackageSassImporter],
},
).css.toString();
}
async function runM3ThemeSchematic(
runner: SchematicTestRunner,
options: Schema,
): Promise<UnitTestTree> {
const app = await createTestApp(runner, {standalone: true});
return runner.runSchematic('theme-color', options, app);
}
beforeEach(() => {
testM3ThemePalette = getPaletteMap();
runner = new SchematicTestRunner(
'@angular/material',
runfiles.resolveWorkspaceRelative('src/material/schematics/collection.json'),
);
});
it('should throw error if given an incorrect color', async () => {
try {
await runM3ThemeSchematic(runner, {
primaryColor: '#fffff',
});
} catch (e) {
expect((e as Error).message).toBe(
'Cannot parse the specified color #fffff. Please verify it is a hex color (ex. #ffffff or ffffff).',
);
}
});
it('should generate m3 theme file', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
});
expect(tree.exists('_theme-colors.scss')).toBe(true);
});
it('should generate m3 theme file at specified path', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
directory: 'projects/',
});
expect(tree.exists('projects/_theme-colors.scss')).toBe(true);
});
it('should generate m3 theme file with correct indentation and formatting', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
});
expect(tree.readText('_theme-colors.scss')).toEqual(getTestTheme());
});
it('should generate themes when provided a primary color', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
});
const generatedSCSS = tree.readText('_theme-colors.scss');
const testSCSS = generateSCSSTheme(
testM3ThemePalette,
'Color palettes are generated from primary: #984061',
);
expect(generatedSCSS).toBe(testSCSS);
expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS));
});
it('should generate themes when provided primary and secondary colors', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
secondaryColor: '#984061',
});
const generatedSCSS = tree.readText('_theme-colors.scss');
// Change test theme palette so that secondary is the same source color as
// primary to match schematic inputs
let testPalette = testM3ThemePalette;
testPalette.set('secondary', testM3ThemePalette.get('primary')!);
const testSCSS = generateSCSSTheme(
testPalette,
'Color palettes are generated from primary: #984061, secondary: #984061',
);
expect(generatedSCSS).toBe(testSCSS);
expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS));
});
it('should generate themes when provided primary, secondary, and tertiary colors', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
secondaryColor: '#984061',
tertiaryColor: '#984061',
});
const generatedSCSS = tree.readText('_theme-colors.scss');
// Change test theme palette so that secondary and tertiary are the same
// source color as primary to match schematic inputs
let testPalette = testM3ThemePalette;
testPalette.set('secondary', testM3ThemePalette.get('primary')!);
testPalette.set('tertiary', testM3ThemePalette.get('primary')!);
const testSCSS = generateSCSSTheme(
testPalette,
'Color palettes are generated from primary: #984061, secondary: #984061, tertiary: #984061',
);
expect(generatedSCSS).toBe(testSCSS);
expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS));
});
it('should generate themes when provided a primary, secondary, tertiary, and neutral colors', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
secondaryColor: '#984061',
tertiaryColor: '#984061',
neutralColor: '#984061',
});
const generatedSCSS = tree.readText('_theme-colors.scss');
// Change test theme palette so that secondary, tertiary, and neutral are
// the same source color as primary to match schematic inputs
let testPalette = testM3ThemePalette;
testPalette.set('secondary', testM3ThemePalette.get('primary')!);
testPalette.set('tertiary', testM3ThemePalette.get('primary')!);
// Neutral's tonal palette has additional tones as opposed to the other color palettes.
let neutralPalette = new Map(testM3ThemePalette.get('primary')!);
neutralPalette.set(4, '#26000f');
neutralPalette.set(6, '#2f0015');
neutralPalette.set(12, '#460022');
neutralPalette.set(17, '#55082c');
neutralPalette.set(22, '#631637');
neutralPalette.set(24, '#691a3c');
neutralPalette.set(87, '#ffcdda');
neutralPalette.set(92, '#ffe1e8');
neutralPalette.set(94, '#ffe8ed');
neutralPalette.set(96, '#fff0f2');
testPalette.set('neutral', neutralPalette);
const testSCSS = generateSCSSTheme(
testPalette,
'Color palettes are generated from primary: #984061, secondary: #984061, tertiary: #984061, neutral: #984061',
);
expect(generatedSCSS).toBe(testSCSS);
expect(transpileTheme(generatedSCSS)).toBe(transpileTheme(testSCSS));
});
it('should be able to generate high contrast overrides mixin', async () => {
const tree = await runM3ThemeSchematic(runner, {
primaryColor: '#984061',
includeHighContrast: true,
});
const generatedSCSS = tree.readText('_theme-colors.scss');
expect(generatedSCSS).toContain(`@mixin high-contrast-overrides`);
});
| |
117250
|
function getTestTheme() {
return `// This file was generated by running 'ng generate @angular/material:theme-color'.
// Proceed with caution if making changes to this file.
@use 'sass:map';
@use '@angular/material' as mat;
// Note: Color palettes are generated from primary: #984061
$_palettes: (
primary: (
0: #000000,
10: #3e001d,
20: #5e1133,
25: #6c1d3e,
30: #7b2949,
35: #893455,
40: #984061,
50: #b6587a,
60: #d57194,
70: #f48bae,
80: #ffb0c8,
90: #ffd9e2,
95: #ffecf0,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
),
secondary: (
0: #000000,
10: #31101d,
20: #4a2531,
25: #56303c,
30: #633b48,
35: #704653,
40: #7e525f,
50: #996a78,
60: #b58392,
70: #d29dac,
80: #efb8c7,
90: #ffd9e2,
95: #ffecf0,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
),
tertiary: (
0: #000000,
10: #331200,
20: #532200,
25: #642a00,
30: #763300,
35: #883d03,
40: #974810,
50: #b66028,
60: #d6783e,
70: #f69256,
80: #ffb68e,
90: #ffdbc9,
95: #ffede5,
98: #fff8f6,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #22191c,
20: #372e30,
25: #43393b,
30: #4f4446,
35: #5b5052,
40: #675b5e,
50: #807477,
60: #9b8d90,
70: #b6a8aa,
80: #d2c3c5,
90: #efdfe1,
95: #fdedef,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
4: #140c0e,
6: #191113,
12: #261d20,
17: #31282a,
22: #3c3235,
24: #413739,
87: #e6d6d9,
92: #f5e4e7,
94: #faeaed,
96: #fff0f2,
),
neutral-variant: (
0: #000000,
10: #25181c,
20: #3c2c31,
25: #47373b,
30: #534247,
35: #604e52,
40: #6c5a5e,
50: #867277,
60: #a18b90,
70: #bca5ab,
80: #d9c0c6,
90: #f6dce2,
95: #ffecf0,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
),
error: (
0: #000000,
10: #410002,
20: #690005,
25: #7e0007,
30: #93000a,
35: #a80710,
40: #ba1a1a,
50: #de3730,
60: #ff5449,
70: #ff897d,
80: #ffb4ab,
90: #ffdad6,
95: #ffedea,
98: #fff8f7,
99: #fffbff,
100: #ffffff,
),
);
$_rest: (
secondary: map.get($_palettes, secondary),
neutral: map.get($_palettes, neutral),
neutral-variant: map.get($_palettes, neutral-variant),
error: map.get($_palettes, error),
);
$primary-palette: map.merge(map.get($_palettes, primary), $_rest);
$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);`;
}
| |
117252
|
# Material 3 Custom Theme schematic
```shell
ng generate @angular/material:theme-color
```
This schematic allows users to create new Material 3 theme palettes based
on custom colors by using [Material Color Utilities](https://github.com/material-foundation/material-color-utilities).
The generated [color palettes](https://m3.material.io/styles/color/roles) are
optimized to have enough contrast to be more accessible. See [Science of Color Design](https://material.io/blog/science-of-color-design) for more information about Material's color design.
For more customization, custom colors can be also be provided for the
secondary, tertiary, and neutral palette colors. It is recommended to choose colors that
are contrastful, Material has more detailed guidance for [accessible design](https://m3.material.io/foundations/accessible-design/patterns).
The output of the schematic will create a file named `_theme-colors.scss` at the
specified directory or the project root with the generated palettes. The exported
palettes (`$primary-palette` and `$tertiary-palette`) can be provided to the `theme` mixin within your theme file to use the custom colors.
```scss
@use '@angular/material' as mat;
@use './path/to/my-theme'; // location of generated file
html {
@include mat.theme(
color: (
primary: my-theme.$primary-palette,
tertiary: my-theme.$tertiary-palette,
),
typography: Roboto,
density: 0,
)
}
```
## High contrast override mixins
High contrast override theme mixins are also generated in the file if specified. These mixins
override the system level variables with high contrast equivalent values from your theme. This is
helpful for users who prefer more contrastful colors for either preference or accessibility reasons.
### Creating one theme for light and dark mode
As of v19, the `theme` mixin can create one theme that detects and adapts to a user if they have
light or dark theme with the [`light-dark` function](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/light-dark).
Apply the `high-contrast-overrides(color-scheme)` mixin wrapped inside `@media (prefers-contrast: more)`.
```scss
@use '@angular/material';
@use './path/to/my-theme'; // location of generated file
html {
// Must specify color-scheme for theme mixin to automatically work
color-scheme: light;
// Create one theme that works automatically for light and dark theme
@include material.theme((
color: (
primary: my-theme.$primary-palette,
tertiary: my-theme.$tertiary-palette,
),
typography: Roboto,
density: 0,
));
// Use high contrast values when users prefer contrast
@media (prefers-contrast: more) {
@include my-theme.high-contrast-overrides(color-scheme);
}
}
```
### Creating separate themes for light and dark mode
You can manually define the light theme and dark theme separately. This is recommended if you need
granular control over when to show each specific theme in your application. Prior to v19, this was
the only way to create light and dark themes.
```scss
@use '@angular/material';
@use './path/to/my-theme'; // location of generated file
html {
// Apply the light theme by default
@include material.theme((
color: (
primary: my-theme.$primary-palette,
tertiary: my-theme.$tertiary-palette,
theme-type: light,
),
typography: Roboto,
density: 0,
));
// Use high contrast light theme colors when users prefer contrast
@media (prefers-contrast: more) {
@include my-theme.high-contrast-overrides(light);
}
// Apply dark theme when users prefer a dark color scheme
@media (prefers-color-scheme: dark) {
@include material.theme((
color: (
primary: my-theme.$primary-palette,
tertiary: my-theme.$tertiary-palette,
theme-type: dark,
),
));
// Use high contrast dark theme colors when users prefers a dark color scheme and contrast
@media (prefers-contrast: more) {
@include my-theme.high-contrast-overrides(dark);
}
}
}
```
## Options
### Required
* `primaryColor` - Color to use for app's primary color palette (Note: the other
palettes described in the Material 3 spec will be automatically chosen based on
your primary palette unless specified, to ensure a harmonious color combination).
### Optional
* `secondaryColor` - Color to use for app's secondary color palette. Defaults to
secondary color generated from Material based on the primary.
* `tertiaryColor` - Color to use for app's tertiary color palette. Defaults to
tertiary color generated from Material based on the primary.
* `neutralColor` - Color to use for app's neutral color palette. Defaults to
neutral color generated from Material based on the primary.
* `includeHighContrast` - Whether to add high contrast override mixins to generated
theme file. Developers can call the mixin when they want to show a high contrast version of their
theme. Defaults to false.
* `directory` - Relative path to a directory within the project that the
generated theme file should be created in. Defaults to the project root.
| |
117255
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Rule, SchematicContext, Tree} from '@angular-devkit/schematics';
import {Schema} from './schema';
import {
argbFromHex,
hexFromArgb,
TonalPalette,
Hct,
DynamicScheme,
DislikeAnalyzer,
TemperatureCache,
} from '@material/material-color-utilities';
// For each color tonal palettes are created using the following hue tones. The
// tonal palettes then get used to create the different color roles (ex.
// on-primary) https://m3.material.io/styles/color/system/how-the-system-works
const HUE_TONES = [0, 10, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 95, 98, 99, 100];
// Map of neutral hues to the previous/next hues that
// can be used to estimate them, in case they're missing.
const NEUTRAL_HUES = new Map<number, {prev: number; next: number}>([
[4, {prev: 0, next: 10}],
[6, {prev: 0, next: 10}],
[12, {prev: 10, next: 20}],
[17, {prev: 10, next: 20}],
[22, {prev: 20, next: 25}],
[24, {prev: 20, next: 25}],
[87, {prev: 80, next: 90}],
[92, {prev: 90, next: 95}],
[94, {prev: 90, next: 95}],
[96, {prev: 95, next: 98}],
]);
// Note: Some of the color tokens refer to additional hue tones, but this only
// applies for the neutral color palette (ex. surface container is neutral
// palette's 94 tone). https://m3.material.io/styles/color/static/baseline
const NEUTRAL_HUE_TONES = [...HUE_TONES, ...NEUTRAL_HUES.keys()];
/**
* Gets color tonal palettes generated by Material from the provided color.
* @param primaryPalette Tonal palette that represents primary.
* @param secondaryPalette Tonal palette that represents secondary.
* @param tertiaryPalette Tonal palette that represents tertiary.
* @param neutralPalette Tonal palette that represents neutral.
* @param neutralVariantPalette Tonal palette that represents neutral variant.
* @param isDark Boolean to represent if the scheme is for a dark or light theme.
* @param contrastLevel Number between -1 and 1 for the contrast level. 0 is the standard contrast
* and 1 represents high contrast.
* @returns Dynamic scheme for provided theme and contrast level
*/
function getMaterialDynamicScheme(
primaryPalette: TonalPalette,
secondaryPalette: TonalPalette,
tertiaryPalette: TonalPalette,
neutralPalette: TonalPalette,
neutralVariantPalette: TonalPalette,
isDark: boolean,
contrastLevel: number,
): DynamicScheme {
return new DynamicScheme({
sourceColorArgb: primaryPalette.keyColor.toInt(),
variant: 6, // Variant.FIDELITY, used number representation since enum is not accessible outside of @material/material-color-utilities
contrastLevel: contrastLevel,
isDark: isDark,
primaryPalette: primaryPalette,
secondaryPalette: secondaryPalette,
tertiaryPalette: tertiaryPalette,
neutralPalette: neutralPalette,
neutralVariantPalette: neutralVariantPalette,
});
}
/**
* Gets the scss representation of the provided color palettes.
* @param colorPalettes Map of colors and their hue tones and values.
* @returns String of the color palettes scss.
*/
function getColorPalettesSCSS(colorPalettes: Map<string, Map<number, string>>): string {
let scss = '(\n';
for (const [variant, palette] of colorPalettes!.entries()) {
scss += ' ' + variant + ': (\n';
for (const [key, value] of palette.entries()) {
scss += ' ' + key + ': ' + value + ',\n';
}
scss += ' ),\n';
}
scss += ');';
return scss;
}
/**
* Gets map of all the color tonal palettes with their tones and colors from provided palettes.
* @param primaryPalette Tonal palette that represents primary.
* @param secondaryPalette Tonal palette that represents secondary.
* @param tertiaryPalette Tonal palette that represents tertiary.
* @param neutralPalette Tonal palette that represents neutral.
* @param neutralVariantPalette Tonal palette that represents neutral variant.
* @param errorPalette Tonal palette that represents error.
* @returns Map with the colors and their hue tones and values.
*/
function getMapFromColorTonalPalettes(
primaryPalette: TonalPalette,
secondaryPalette: TonalPalette,
tertiaryPalette: TonalPalette,
neutralPalette: TonalPalette,
neutralVariantPalette: TonalPalette,
errorPalette: TonalPalette,
) {
const tonalPalettes = {
primary: primaryPalette,
secondary: secondaryPalette,
tertiary: tertiaryPalette,
neutral: neutralPalette,
neutralVariant: neutralVariantPalette,
error: errorPalette,
};
const palettes: Map<string, Map<number, string>> = new Map();
for (const [key, palette] of Object.entries(tonalPalettes)) {
const paletteKey = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
const tones = paletteKey === 'neutral' ? NEUTRAL_HUE_TONES : HUE_TONES;
const colorPalette: Map<number, string> = new Map();
for (const tone of tones) {
const color = hexFromArgb(palette.tone(tone));
colorPalette.set(tone, color);
}
palettes.set(paletteKey, colorPalette);
}
return palettes;
}
/**
* Gets the generated scss from the provided color palettes and theme types.
* @param colorPalettes Map of colors and their hue tones and values.
* @param colorComment Comment with original hex colors used to generate palettes.
* @returns String of the generated theme scss.
*/
export function generateSCSSTheme(
colorPalettes: Map<string, Map<number, string>>,
colorComment: string,
): string {
let scss = [
"// This file was generated by running 'ng generate @angular/material:theme-color'.",
'// Proceed with caution if making changes to this file.',
'',
"@use 'sass:map';",
"@use '@angular/material' as mat;",
'',
'// Note: ' + colorComment,
'$_palettes: ' + getColorPalettesSCSS(colorPalettes),
'',
'$_rest: (',
' secondary: map.get($_palettes, secondary),',
' neutral: map.get($_palettes, neutral),',
' neutral-variant: map.get($_palettes, neutral-variant),',
' error: map.get($_palettes, error),',
');',
'',
'$primary-palette: map.merge(map.get($_palettes, primary), $_rest);',
'$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);',
];
return scss.join('\n');
}
/**
* Gets map of system variables and their high contrast values.
* @param primaryPalette Tonal palette that represents primary.
* @param secondaryPalette Tonal palette that represents secondary.
* @param tertiaryPalette Tonal palette that represents tertiary.
* @param neutralPalette Tonal palette that represents neutral.
* @param neutralVariantPalette Tonal palette that represents neutral variant.
* @param isDark Boolean to represent if the scheme is for a dark or light theme.
* @returns Map of system variables names and their high contrast values.
*/
| |
117266
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/** Create custom theme for the given application configuration. */
export function createCustomTheme(name: string = 'app') {
return `
// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
// Plus imports for other components in your app.
// Define the theme object.
$${name}-theme: mat.define-theme((
color: (
theme-type: light,
primary: mat.$azure-palette,
tertiary: mat.$blue-palette,
),
density: (
scale: 0,
)
));
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
:root {
@include mat.all-component-themes($${name}-theme);
}
// Comment out the line below if you want to use the pre-defined typography utility classes.
// For more information: https://material.angular.io/guide/typography#using-typography-styles-in-your-application.
// @include mat.typography-hierarchy($${name}-theme);
// Comment out the line below if you want to use the deprecated \`color\` inputs.
// @include mat.color-variants-backwards-compatibility($${name}-theme);
`;
}
| |
117268
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Rule, SchematicsException, Tree} from '@angular-devkit/schematics';
import {
appendHtmlElementToHead,
getProjectFromWorkspace,
getProjectIndexFiles,
} from '@angular/cdk/schematics';
import {getWorkspace} from '@schematics/angular/utility/workspace';
import {Schema} from '../schema';
/** Adds the Material Design fonts to the index HTML file. */
export function addFontsToIndex(options: Schema): Rule {
return async (host: Tree) => {
const workspace = await getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const projectIndexFiles = getProjectIndexFiles(project);
if (!projectIndexFiles.length) {
throw new SchematicsException('No project index HTML file could be found.');
}
const fonts = [
'https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap',
'https://fonts.googleapis.com/icon?family=Material+Icons',
];
projectIndexFiles.forEach(indexFilePath => {
fonts.forEach(font => {
appendHtmlElementToHead(host, indexFilePath, `<link href="${font}" rel="stylesheet">`);
});
});
};
}
| |
117326
|
extends VBoxContainer
const ROT_SPEED = 0.003
const ZOOM_SPEED = 0.5
const MAIN_BUTTONS = MOUSE_BUTTON_MASK_LEFT | MOUSE_BUTTON_MASK_MIDDLE | MOUSE_BUTTON_MASK_RIGHT
@export var camera: Camera3D
@export var camera_holder: Node3D
@export var rotation_x: Node3D
@export var node_to_move: Node3D
@export var rigid_body: RigidBody3D
@onready var zoom := camera.position.z
var base_height: int = ProjectSettings.get_setting("display/window/size/viewport_height")
@onready var rot_x := rotation_x.rotation.x
@onready var rot_y := camera_holder.rotation.y
func _ready() -> void:
if OS.has_feature("double"):
%HelpLabel.text = "Double precision is enabled in this engine build.\nNo shaking should occur at high coordinate levels\n(±65,536 or more on any axis)."
%HelpLabel.add_theme_color_override("font_color", Color(0.667, 1, 0.667))
func _process(delta: float) -> void:
%Coordinates.text = "X: [color=#fb9]%f[/color]\nY: [color=#bfa]%f[/color]\nZ: [color=#9cf]%f[/color]" % [node_to_move.position.x, node_to_move.position.y, node_to_move.position.z]
if %IncrementX.button_pressed:
node_to_move.position.x += 10_000 * delta
if %IncrementY.button_pressed:
node_to_move.position.y += 100_000 * delta
if %IncrementZ.button_pressed:
node_to_move.position.z += 1_000_000 * delta
func _input(event: InputEvent) -> void:
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
zoom -= ZOOM_SPEED
if event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
zoom += ZOOM_SPEED
zoom = clampf(zoom, 4, 15)
camera.position.z = zoom
if event is InputEventMouseMotion and event.button_mask & MAIN_BUTTONS:
# Compensate motion speed to be resolution-independent (based on the window height).
var relative_motion: Vector2 = event.relative * DisplayServer.window_get_size().y / base_height
rot_y -= relative_motion.x * ROT_SPEED
rot_x -= relative_motion.y * ROT_SPEED
rot_x = clampf(rot_x, -1.4, 0.16)
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
func _on_go_to_button_pressed(x_position: int) -> void:
if x_position == 0:
# Reset all coordinates, not just X.
node_to_move.position = Vector3.ZERO
else:
node_to_move.position.x = x_position
func _on_open_documentation_pressed() -> void:
OS.shell_open("https://docs.godotengine.org/en/latest/tutorials/physics/large_world_coordinates.html")
| |
117350
|
# This node converts a 3D position to 2D using a 2.5D transformation matrix.
# The transformation of its 2D form is controlled by its 3D child.
@tool
@icon("res://addons/node25d/icons/node_25d_icon.png")
class_name Node25D
extends Node2D
# SCALE is the number of 2D units in one 3D unit. Ideally, but not necessarily, an integer.
const SCALE = 32
# Exported spatial position for editor usage.
@export var spatial_position: Vector3:
get:
# TODO: Manually copy the code from this method.
return get_spatial_position()
set(value):
# TODO: Manually copy the code from this method.
set_spatial_position(value)
# GDScript throws errors when Basis25D is its own structure.
# There is a broken implementation in a hidden folder.
# https://github.com/godotengine/godot/issues/21461
# https://github.com/godotengine/godot-proposals/issues/279
var _basisX: Vector2
var _basisY: Vector2
var _basisZ: Vector2
# Cache the spatial stuff for internal use.
var _spatial_position: Vector3
var _spatial_node: Node3D
# These are separated in case anyone wishes to easily extend Node25D.
func _ready():
Node25D_ready()
func _process(_delta):
Node25D_process()
# Call this method in _ready, or before Node25D_process is first ran.
func Node25D_ready():
_spatial_node = get_child(0)
# Changing the values here will change the default for all Node25D instances.
_basisX = SCALE * Vector2(1, 0)
_basisY = SCALE * Vector2(0, -0.70710678118)
_basisZ = SCALE * Vector2(0, 0.70710678118)
# Call this method in _process, or whenever the position of this object changes.
func Node25D_process():
_check_view_mode()
if _spatial_node == null:
return
_spatial_position = _spatial_node.position
var flat_pos = _spatial_position.x * _basisX
flat_pos += _spatial_position.y * _basisY
flat_pos += _spatial_position.z * _basisZ
global_position = flat_pos
func get_basis():
return [_basisX, _basisY, _basisZ]
func get_spatial_position():
if not _spatial_node:
_spatial_node = get_child(0)
return _spatial_node.position
func set_spatial_position(value):
_spatial_position = value
if _spatial_node:
_spatial_node.position = value
elif get_child_count() > 0:
_spatial_node = get_child(0)
# Change the basis based on the view_mode_index argument.
# This can be changed or removed in actual games where you only need one view mode.
func set_view_mode(view_mode_index):
match view_mode_index:
0: # 45 Degrees
_basisX = SCALE * Vector2(1, 0)
_basisY = SCALE * Vector2(0, -0.70710678118)
_basisZ = SCALE * Vector2(0, 0.70710678118)
1: # Isometric
_basisX = SCALE * Vector2(0.86602540378, 0.5)
_basisY = SCALE * Vector2(0, -1)
_basisZ = SCALE * Vector2(-0.86602540378, 0.5)
2: # Top Down
_basisX = SCALE * Vector2(1, 0)
_basisY = SCALE * Vector2(0, 0)
_basisZ = SCALE * Vector2(0, 1)
3: # Front Side
_basisX = SCALE * Vector2(1, 0)
_basisY = SCALE * Vector2(0, -1)
_basisZ = SCALE * Vector2(0, 0)
4: # Oblique Y
_basisX = SCALE * Vector2(1, 0)
_basisY = SCALE * Vector2(-0.70710678118, -0.70710678118)
_basisZ = SCALE * Vector2(0, 1)
5: # Oblique Z
_basisX = SCALE * Vector2(1, 0)
_basisY = SCALE * Vector2(0, -1)
_basisZ = SCALE * Vector2(-0.70710678118, 0.70710678118)
# Check if anyone presses the view mode buttons and change the basis accordingly.
# This can be changed or removed in actual games where you only need one view mode.
func _check_view_mode():
if not Engine.is_editor_hint():
if Input.is_action_just_pressed(&"forty_five_mode"):
set_view_mode(0)
elif Input.is_action_just_pressed(&"isometric_mode"):
set_view_mode(1)
elif Input.is_action_just_pressed(&"top_down_mode"):
set_view_mode(2)
elif Input.is_action_just_pressed(&"front_side_mode"):
set_view_mode(3)
elif Input.is_action_just_pressed(&"oblique_y_mode"):
set_view_mode(4)
elif Input.is_action_just_pressed(&"oblique_z_mode"):
set_view_mode(5)
# Used by YSort25D
static func y_sort(a: Node25D, b: Node25D):
return a._spatial_position.y < b._spatial_position.y
static func y_sort_slight_xz(a: Node25D, b: Node25D):
var a_index = a._spatial_position.y + 0.001 * (a._spatial_position.x + a._spatial_position.z)
var b_index = b._spatial_position.y + 0.001 * (b._spatial_position.x + b._spatial_position.z)
return a_index < b_index
| |
117366
|
@tool
extends Control
var zoom_level := 0
var is_panning = false
var pan_center: Vector2
var viewport_center: Vector2
var view_mode_index := 0
var editor_interface: EditorInterface # Set in node25d_plugin.gd
var moving = false
@onready var viewport_2d = $Viewport2D
@onready var viewport_overlay = $ViewportOverlay
@onready var view_mode_button_group: ButtonGroup = $"../TopBar/ViewModeButtons/45Degree".button_group
@onready var zoom_label: Label = $"../TopBar/Zoom/ZoomPercent"
@onready var gizmo_25d_scene = preload("res://addons/node25d/main_screen/gizmo_25d.tscn")
func _ready() -> void:
# Give Godot a chance to fully load the scene. Should take two frames.
for i in 2:
await get_tree().process_frame
var edited_scene_root = get_tree().edited_scene_root
if not edited_scene_root:
# Godot hasn't finished loading yet, so try loading the plugin again.
editor_interface.set_plugin_enabled("node25d", false)
editor_interface.set_plugin_enabled("node25d", true)
return
# Alright, we're loaded up. Now check if we have a valid world and assign it.
var world_2d = edited_scene_root.get_viewport().world_2d
if world_2d == get_viewport().world_2d:
return # This is the MainScreen25D scene opened in the editor!
viewport_2d.world_2d = world_2d
func _process(_delta: float) -> void:
if not editor_interface: # Something's not right... bail!
return
# View mode polling.
var view_mode_changed_this_frame := false
var new_view_mode := -1
if view_mode_button_group.get_pressed_button():
new_view_mode = view_mode_button_group.get_pressed_button().get_index()
if view_mode_index != new_view_mode:
view_mode_index = new_view_mode
view_mode_changed_this_frame = true
_recursive_change_view_mode(get_tree().edited_scene_root)
# Zooming.
if Input.is_mouse_button_pressed(MOUSE_BUTTON_WHEEL_UP):
zoom_level += 1
elif Input.is_mouse_button_pressed(MOUSE_BUTTON_WHEEL_DOWN):
zoom_level -= 1
var zoom := _get_zoom_amount()
# SubViewport size.
var vp_size := get_global_rect().size
viewport_2d.size = vp_size
viewport_overlay.size = vp_size
# SubViewport transform.
var viewport_trans := Transform2D.IDENTITY
viewport_trans.x *= zoom
viewport_trans.y *= zoom
viewport_trans.origin = viewport_trans.basis_xform(viewport_center) + size / 2
viewport_2d.canvas_transform = viewport_trans
viewport_overlay.canvas_transform = viewport_trans
# Delete unused gizmos.
var selection := editor_interface.get_selection().get_selected_nodes()
var gizmos := viewport_overlay.get_children()
for gizmo in gizmos:
var contains := false
for selected in selection:
if selected == gizmo.node_25d and not view_mode_changed_this_frame:
contains = true
if not contains:
gizmo.queue_free()
# Add new gizmos.
for selected in selection:
if selected is Node25D:
_ensure_node25d_has_gizmo(selected, gizmos)
# Update gizmo zoom.
for gizmo in gizmos:
gizmo.set_zoom(zoom)
func _ensure_node25d_has_gizmo(node: Node25D, gizmos: Array[Node]) -> void:
var new = true
for gizmo in gizmos:
if node == gizmo.node_25d:
return
var gizmo = gizmo_25d_scene.instantiate()
viewport_overlay.add_child(gizmo)
gizmo.setup(node)
# This only accepts input when the mouse is inside of the 2.5D viewport.
func _gui_input(event: InputEvent) -> void:
if event is InputEventMouseButton:
if event.is_pressed():
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
zoom_level += 1
accept_event()
elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
zoom_level -= 1
accept_event()
elif event.button_index == MOUSE_BUTTON_MIDDLE:
is_panning = true
pan_center = viewport_center - event.position / _get_zoom_amount()
accept_event()
elif event.button_index == MOUSE_BUTTON_LEFT:
var overlay_children := viewport_overlay.get_children()
for overlay_child in overlay_children:
overlay_child.wants_to_move = true
accept_event()
elif event.button_index == MOUSE_BUTTON_MIDDLE:
is_panning = false
accept_event()
elif event.button_index == MOUSE_BUTTON_LEFT:
var overlay_children := viewport_overlay.get_children()
for overlay_child in overlay_children:
overlay_child.wants_to_move = false
accept_event()
elif event is InputEventMouseMotion:
if is_panning:
viewport_center = pan_center + event.position / _get_zoom_amount()
accept_event()
func _recursive_change_view_mode(current_node: Node) -> void:
if not current_node:
return
if current_node.has_method("set_view_mode"):
current_node.set_view_mode(view_mode_index)
for child in current_node.get_children():
_recursive_change_view_mode(child)
func _get_zoom_amount() -> float:
const THIRTEENTH_ROOT_OF_2 = 1.05476607648
var zoom_amount = pow(THIRTEENTH_ROOT_OF_2, zoom_level)
zoom_label.text = str(round(zoom_amount * 1000) / 10) + "%"
return zoom_amount
func _on_ZoomOut_pressed() -> void:
zoom_level -= 1
func _on_ZoomIn_pressed() -> void:
zoom_level += 1
func _on_ZoomReset_pressed() -> void:
zoom_level = 0
| |
117403
|
# Handles Player-specific behavior like moving. We calculate such things with CharacterBody3D.
class_name PlayerMath25D # No icon necessary
extends CharacterBody3D
var vertical_speed := 0.0
var isometric_controls := true
@onready var _parent_node25d: Node25D = get_parent()
func _physics_process(delta: float) -> void:
if Input.is_action_pressed(&"exit"):
get_tree().quit()
if Input.is_action_just_pressed(&"view_cube_demo"):
get_tree().change_scene_to_file("res://assets/cube/cube.tscn")
return
if Input.is_action_just_pressed(&"toggle_isometric_controls"):
isometric_controls = not isometric_controls
if Input.is_action_just_pressed(&"reset_position") or position.y <= -100:
# Reset player position if the player fell down into the void.
transform = Transform3D(Basis(), Vector3.UP * 0.5)
vertical_speed = 0
else:
_horizontal_movement(delta)
_vertical_movement(delta)
# Checks WASD and Shift for horizontal movement via move_and_slide.
func _horizontal_movement(_delta: float) -> void:
var local_x := Vector3.RIGHT
var local_z := Vector3.BACK
if isometric_controls and is_equal_approx(Node25D.SCALE * 0.86602540378, _parent_node25d.get_basis()[0].x):
local_x = Vector3(0.70710678118, 0, -0.70710678118)
local_z = Vector3(0.70710678118, 0, 0.70710678118)
# Gather player input and add directional movement to a Vector3 variable.
var movement_vec2 := Input.get_vector(&"move_left", &"move_right", &"move_forward", &"move_back")
var move_dir: Vector3 = local_x * movement_vec2.x + local_z * movement_vec2.y
velocity = move_dir * 10
if Input.is_action_pressed(&"movement_modifier"):
velocity /= 2
move_and_slide()
# Checks Jump and applies gravity and vertical speed via move_and_collide.
func _vertical_movement(delta: float) -> void:
if Input.is_action_just_pressed(&"jump"):
vertical_speed = 60
vertical_speed -= delta * 240 # Gravity
var k := move_and_collide(Vector3.UP * vertical_speed * delta)
if k != null:
vertical_speed = 0
| |
117404
|
@tool
extends Sprite2D
const ANIMATION_FRAMERATE = 15
var _direction := 0
var _progress := 0.0
var _parent_node25d: Node25D
var _parent_math: PlayerMath25D
@onready var _stand: Texture2D = preload("res://assets/player/textures/stand.png")
@onready var _jump: Texture2D = preload("res://assets/player/textures/jump.png")
@onready var _run: Texture2D = preload("res://assets/player/textures/run.png")
func _ready() -> void:
_parent_node25d = get_parent()
_parent_math = _parent_node25d.get_child(0)
func _process(delta: float) -> void:
if Engine.is_editor_hint():
return # Don't run this in the editor.
_sprite_basis()
var movement := _check_movement() # Always run to get direction, but don't always use return bool.
# Test-only move and collide, check if the player is on the ground.
var k := _parent_math.move_and_collide(Vector3.DOWN * 10 * delta, true, true, true)
if k != null:
if movement:
hframes = 6
texture = _run
if Input.is_action_pressed(&"movement_modifier"):
delta /= 2
_progress = fmod((_progress + ANIMATION_FRAMERATE * delta), 6)
frame = _direction * 6 + int(_progress)
else:
hframes = 1
texture = _stand
_progress = 0
frame = _direction
else:
hframes = 2
texture = _jump
_progress = 0
var jumping := 1 if _parent_math.vertical_speed < 0 else 0
frame = _direction * 2 + jumping
func set_view_mode(view_mode_index: int) -> void:
match view_mode_index:
0: # 45 Degrees
transform.x = Vector2(1, 0)
transform.y = Vector2(0, 0.75)
1: # Isometric
transform.x = Vector2(1, 0)
transform.y = Vector2(0, 1)
2: # Top Down
transform.x = Vector2(1, 0)
transform.y = Vector2(0, 0.5)
3: # Front Side
transform.x = Vector2(1, 0)
transform.y = Vector2(0, 1)
4: # Oblique Y
transform.x = Vector2(1, 0)
transform.y = Vector2(0.75, 0.75)
5: # Oblique Z
transform.x = Vector2(1, 0.25)
transform.y = Vector2(0, 1)
# Change the 2D basis of the sprite to try and make it "fit" multiple view modes.
func _sprite_basis() -> void:
if not Engine.is_editor_hint():
if Input.is_action_pressed(&"forty_five_mode"):
set_view_mode(0)
elif Input.is_action_pressed(&"isometric_mode"):
set_view_mode(1)
elif Input.is_action_pressed(&"top_down_mode"):
set_view_mode(2)
elif Input.is_action_pressed(&"front_side_mode"):
set_view_mode(3)
elif Input.is_action_pressed(&"oblique_y_mode"):
set_view_mode(4)
elif Input.is_action_pressed(&"oblique_z_mode"):
set_view_mode(5)
# This method returns a bool but if true it also outputs to the direction variable.
func _check_movement() -> bool:
# Gather player input and store movement to these int variables. Note: These indeed have to be integers.
var x := 0
var z := 0
if Input.is_action_pressed(&"move_right"):
x += 1
if Input.is_action_pressed(&"move_left"):
x -= 1
if Input.is_action_pressed(&"move_forward"):
z -= 1
if Input.is_action_pressed(&"move_back"):
z += 1
# Check for isometric controls and add more to movement accordingly.
# For efficiency, only check the X axis since this X axis value isn't used anywhere else.
if not _parent_math.isometric_controls and is_equal_approx(Node25D.SCALE * 0.86602540378, _parent_node25d.get_basis()[0].x):
if Input.is_action_pressed(&"move_right"):
z += 1
if Input.is_action_pressed(&"move_left"):
z -= 1
if Input.is_action_pressed(&"move_forward"):
x += 1
if Input.is_action_pressed(&"move_back"):
x -= 1
# Set the direction based on which inputs were pressed.
if x == 0:
if z == 0:
return false # No movement.
elif z > 0:
_direction = 0
else:
_direction = 4
elif x > 0:
if z == 0:
_direction = 2
flip_h = true
elif z > 0:
_direction = 1
flip_h = true
else:
_direction = 3
flip_h = true
else:
if z == 0:
_direction = 2
flip_h = false
elif z > 0:
_direction = 1
flip_h = false
else:
_direction = 3
flip_h = false
return true # There is movement.
| |
117405
|
[gd_scene load_steps=6 format=4 uid="uid://bg27d8sfehmr4"]
[ext_resource type="Script" path="res://addons/node25d/node_25d.gd" id="1"]
[ext_resource type="Script" path="res://assets/player/player_math_25d.gd" id="3"]
[ext_resource type="Texture2D" uid="uid://bfdfertqyhf1u" path="res://assets/player/textures/jump.png" id="4"]
[ext_resource type="Script" path="res://assets/player/player_sprite.gd" id="5"]
[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_b17hs"]
[node name="Player25D" type="Node2D"]
z_index = 100
position = Vector2(0, -11.3137)
script = ExtResource("1")
spatial_position = Vector3(0, 0.5, 0)
[node name="PlayerMath25D" type="CharacterBody3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 0)
script = ExtResource("3")
[node name="CollisionShape3D" type="CollisionShape3D" parent="PlayerMath25D"]
shape = SubResource("CapsuleShape3D_b17hs")
[node name="PlayerSprite" type="Sprite2D" parent="."]
z_index = 1
scale = Vector2(1, 0.75)
texture = ExtResource("4")
offset = Vector2(0, 4)
hframes = 2
vframes = 5
script = ExtResource("5")
[node name="PlayerCamera" type="Camera2D" parent="PlayerSprite"]
| |
117410
|
func _ready() -> void:
# Grab focus so that the list can be scrolled (for keyboard/controller-friendly navigation).
rtl.grab_focus()
add_header("Audio")
add_line("Mix rate", "%d Hz" % AudioServer.get_mix_rate())
add_line("Output latency", "%f ms" % (AudioServer.get_output_latency() * 1000))
add_line("Output device list", ", ".join(AudioServer.get_output_device_list()))
add_line("Capture device list", ", ".join(AudioServer.get_input_device_list()))
add_line("Connected MIDI inputs", scan_midi_inputs())
add_header("Date and time")
add_line("Date and time (local)", Time.get_datetime_string_from_system(false, true))
add_line("Date and time (UTC)", Time.get_datetime_string_from_system(true, true))
add_line("Date (local)", Time.get_date_string_from_system(false))
add_line("Date (UTC)", Time.get_date_string_from_system(true))
add_line("Time (local)", Time.get_time_string_from_system(false))
add_line("Time (UTC)", Time.get_time_string_from_system(true))
add_line("Timezone", Time.get_time_zone_from_system())
add_line("UNIX time", Time.get_unix_time_from_system())
add_header("Display")
add_line("Screen count", DisplayServer.get_screen_count())
add_line("DPI", DisplayServer.screen_get_dpi())
add_line("Scale factor", DisplayServer.screen_get_scale())
add_line("Maximum scale factor", DisplayServer.screen_get_max_scale())
add_line("Startup screen position", DisplayServer.screen_get_position())
add_line("Startup screen size", DisplayServer.screen_get_size())
add_line("Startup screen refresh rate", ("%f Hz" % DisplayServer.screen_get_refresh_rate()) if DisplayServer.screen_get_refresh_rate() > 0.0 else "")
add_line("Usable (safe) area rectangle", DisplayServer.get_display_safe_area())
add_line("Screen orientation", [
"Landscape",
"Portrait",
"Landscape (reverse)",
"Portrait (reverse)",
"Landscape (defined by sensor)",
"Portrait (defined by sensor)",
"Defined by sensor",
][DisplayServer.screen_get_orientation()])
add_header("Engine")
add_line("Version", Engine.get_version_info()["string"])
add_line("Compiled for architecture", Engine.get_architecture_name())
add_line("Command-line arguments", str(OS.get_cmdline_args()))
add_line("Is debug build", OS.is_debug_build())
add_line("Executable path", OS.get_executable_path())
add_line("User data directory", OS.get_user_data_dir())
add_line("Filesystem is persistent", OS.is_userfs_persistent())
add_line("Process ID (PID)", OS.get_process_id())
add_line("Main thread ID", OS.get_main_thread_id())
add_line("Thread caller ID", OS.get_thread_caller_id())
add_line("Memory information", OS.get_memory_info())
add_line("Static memory usage", OS.get_static_memory_usage())
add_line("Static memory peak usage", OS.get_static_memory_peak_usage())
add_header("Environment")
add_line("Value of `PATH`", OS.get_environment("PATH"))
# Check for case-sensitivity behavior across platforms.
add_line("Value of `path`", OS.get_environment("path"))
add_header("Hardware")
add_line("Model name", OS.get_model_name())
add_line("Processor name", OS.get_processor_name())
add_line("Processor count", OS.get_processor_count())
add_line("Device unique ID", OS.get_unique_id())
add_header("Input")
add_line("Device has touch screen", DisplayServer.is_touchscreen_available())
var has_virtual_keyboard := DisplayServer.has_feature(DisplayServer.FEATURE_VIRTUAL_KEYBOARD)
add_line("Device has virtual keyboard", has_virtual_keyboard)
if has_virtual_keyboard:
add_line("Virtual keyboard height", DisplayServer.virtual_keyboard_get_height())
add_header("Localization")
add_line("Locale", OS.get_locale())
add_line("Language", OS.get_locale_language())
add_header("Mobile")
add_line("Granted permissions", OS.get_granted_permissions())
add_header(".NET (C#)")
var csharp_enabled := ResourceLoader.exists("res://CSharpTest.cs")
add_line("Mono module enabled", "Yes" if csharp_enabled else "No")
if csharp_enabled:
csharp_test.set_script(load("res://CSharpTest.cs"))
add_line("Operating system", csharp_test.OperatingSystem())
add_line("Platform type", csharp_test.PlatformType())
add_header("Software")
add_line("OS name", OS.get_name())
add_line("OS version", OS.get_version())
add_line("Distribution name", OS.get_distribution_name())
add_line("System dark mode supported", DisplayServer.is_dark_mode_supported())
add_line("System dark mode enabled", DisplayServer.is_dark_mode())
add_line("System accent color", "#%s" % DisplayServer.get_accent_color().to_html())
add_line("System fonts", "%d fonts available" % OS.get_system_fonts().size())
add_line("System font path (\"sans-serif\")", OS.get_system_font_path("sans-serif"))
add_line("System font path (\"sans-serif\") for English text", ", ".join(OS.get_system_font_path_for_text("sans-serif", "Hello")))
add_line("System font path (\"sans-serif\") for Chinese text", ", ".join(OS.get_system_font_path_for_text("sans-serif", "你好")))
add_line("System font path (\"sans-serif\") for Japanese text", ", ".join(OS.get_system_font_path_for_text("sans-serif", "こんにちは")))
add_header("Security")
add_line("Is sandboxed", OS.is_sandboxed())
add_line("Entropy (8 random bytes)", OS.get_entropy(8))
add_line("System CA certificates", ("Available (%d bytes)" % OS.get_system_ca_certificates().length()) if not OS.get_system_ca_certificates().is_empty() else "Not available")
add_header("Engine directories")
add_line("User data", OS.get_data_dir())
add_line("Configuration", OS.get_config_dir())
add_line("Cache", OS.get_cache_dir())
add_header("System directories")
add_line("Desktop", OS.get_system_dir(OS.SYSTEM_DIR_DESKTOP))
add_line("DCIM", OS.get_system_dir(OS.SYSTEM_DIR_DCIM))
add_line("Documents", OS.get_system_dir(OS.SYSTEM_DIR_DOCUMENTS))
add_line("Downloads", OS.get_system_dir(OS.SYSTEM_DIR_DOWNLOADS))
add_line("Movies", OS.get_system_dir(OS.SYSTEM_DIR_MOVIES))
add_line("Music", OS.get_system_dir(OS.SYSTEM_DIR_MUSIC))
add_line("Pictures", OS.get_system_dir(OS.SYSTEM_DIR_PICTURES))
add_line("Ringtones", OS.get_system_dir(OS.SYSTEM_DIR_RINGTONES))
add_header("Video")
add_line("Adapter name", RenderingServer.get_video_adapter_name())
add_line("Adapter vendor", RenderingServer.get_video_adapter_vendor())
if ProjectSettings.get_setting_with_override("rendering/renderer/rendering_method") != "gl_compatibility":
# Querying the adapter type isn't supported in Compatibility.
add_line("Adapter type", [
"Other (Unknown)",
"Integrated",
"Discrete",
"Virtual",
"CPU",
][RenderingServer.get_video_adapter_type()])
add_line("Adapter graphics API version", RenderingServer.get_video_adapter_api_version())
var video_adapter_driver_info := OS.get_video_adapter_driver_info()
if video_adapter_driver_info.size() > 0:
add_line("Adapter driver name", video_adapter_driver_info[0])
if video_adapter_driver_info.size() > 1:
add_line("Adapter driver version", video_adapter_driver_info[1])
| |
117414
|
extends Node
func _on_open_shell_web_pressed() -> void:
OS.shell_open("https://example.com")
func _on_open_shell_folder_pressed() -> void:
var path := OS.get_environment("HOME")
if path == "":
# Windows-specific.
path = OS.get_environment("USERPROFILE")
if OS.get_name() == "macOS":
# MacOS-specific.
path = "file://" + path
OS.shell_show_in_file_manager(path)
func _on_change_window_title_pressed() -> void:
DisplayServer.window_set_title("Modified window title. Unicode characters for testing: é € × Ù ¨")
func _on_change_window_icon_pressed() -> void:
if not DisplayServer.has_feature(DisplayServer.FEATURE_ICON):
OS.alert("Changing the window icon is not supported by the current display server (%s)." % DisplayServer.get_name())
return
var image := Image.create(128, 128, false, Image.FORMAT_RGB8)
image.fill(Color(1, 0.6, 0.3))
DisplayServer.set_icon(image)
func _on_move_window_to_foreground_pressed() -> void:
DisplayServer.window_set_title("Will move window to foreground in 5 seconds, try unfocusing the window...")
await get_tree().create_timer(5).timeout
DisplayServer.window_move_to_foreground()
# Restore the previous window title.
DisplayServer.window_set_title(ProjectSettings.get_setting("application/config/name"))
func _on_request_attention_pressed() -> void:
DisplayServer.window_set_title("Will request attention in 5 seconds, try unfocusing the window...")
await get_tree().create_timer(5).timeout
DisplayServer.window_request_attention()
# Restore the previous window title.
DisplayServer.window_set_title(ProjectSettings.get_setting("application/config/name"))
func _on_vibrate_device_short_pressed() -> void:
Input.vibrate_handheld(200)
func _on_vibrate_device_long_pressed() -> void:
Input.vibrate_handheld(1000)
func _on_add_global_menu_items_pressed() -> void:
if not DisplayServer.has_feature(DisplayServer.FEATURE_GLOBAL_MENU):
OS.alert("Global menus are not supported by the current display server (%s)." % DisplayServer.get_name())
return
# Add a menu to the main menu bar.
DisplayServer.global_menu_add_submenu_item("_main", "Hello", "_main/Hello")
DisplayServer.global_menu_add_item(
"_main/Hello",
"World",
func(tag: String) -> void: print("Clicked main 1 " + str(tag)),
func(tag: String) -> void: print("Key main 1 " + str(tag)),
null,
(KEY_MASK_META | KEY_1) as Key
)
DisplayServer.global_menu_add_separator("_main/Hello")
DisplayServer.global_menu_add_item("_main/Hello", "World2", func(tag: String) -> void: print("Clicked main 2 " + str(tag)))
# Add a menu to the Dock context menu.
DisplayServer.global_menu_add_submenu_item("_dock", "Hello", "_dock/Hello")
DisplayServer.global_menu_add_item("_dock/Hello", "World", func(tag: String) -> void: print("Clicked dock 1 " + str(tag)))
DisplayServer.global_menu_add_separator("_dock/Hello")
DisplayServer.global_menu_add_item("_dock/Hello", "World2", func(tag: String) -> void: print("Clicked dock 2 " + str(tag)))
func _on_remove_global_menu_item_pressed() -> void:
if not DisplayServer.has_feature(DisplayServer.FEATURE_GLOBAL_MENU):
OS.alert("Global menus are not supported by the current display server (%s)." % DisplayServer.get_name())
return
DisplayServer.global_menu_remove_item("_main/Hello", 2)
DisplayServer.global_menu_remove_item("_main/Hello", 1)
DisplayServer.global_menu_remove_item("_main/Hello", 0)
DisplayServer.global_menu_remove_item("_main", 0)
DisplayServer.global_menu_remove_item("_dock/Hello", 2)
DisplayServer.global_menu_remove_item("_dock/Hello", 1)
DisplayServer.global_menu_remove_item("_dock/Hello", 0)
DisplayServer.global_menu_remove_item("_dock", 0)
func _on_get_clipboard_pressed() -> void:
if not DisplayServer.has_feature(DisplayServer.FEATURE_CLIPBOARD):
OS.alert("Clipboard I/O is not supported by the current display server (%s)." % DisplayServer.get_name())
return
OS.alert("Clipboard contents:\n\n%s" % DisplayServer.clipboard_get())
func _on_set_clipboard_pressed() -> void:
if not DisplayServer.has_feature(DisplayServer.FEATURE_CLIPBOARD):
OS.alert("Clipboard I/O is not supported by the current display server (%s)." % DisplayServer.get_name())
return
DisplayServer.clipboard_set("Modified clipboard contents. Unicode characters for testing: é € × Ù ¨")
func _on_display_alert_pressed() -> void:
OS.alert("Hello from Godot! Close this dialog to resume the main window.")
func _on_kill_current_process_pressed() -> void:
OS.kill(OS.get_process_id())
| |
117492
|
extends Area3D
var taken := false
func _on_coin_body_enter(body: Node) -> void:
if not taken and body is Player:
$Animation.play(&"take")
taken = true
# We've already checked whether the colliding body is a Player, which has a `coins` property.
# As a result, we can safely increment its `coins` property.
body.coins += 1
| |
117587
|
class_name Player
extends CharacterBody3D
enum _Anim {
FLOOR,
AIR,
}
const SHOOT_TIME = 1.5
const SHOOT_SCALE = 2.0
const CHAR_SCALE = Vector3(0.3, 0.3, 0.3)
const MAX_SPEED = 6.0
const TURN_SPEED = 40.0
const JUMP_VELOCITY = 12.5
const BULLET_SPEED = 20.0
const AIR_IDLE_DEACCEL = false
const ACCEL = 14.0
const DEACCEL = 14.0
const AIR_ACCEL_FACTOR = 0.5
const SHARP_TURN_THRESHOLD = deg_to_rad(140.0)
var movement_dir := Vector3()
var jumping := false
var prev_shoot := false
var shoot_blend := 0.0
# Number of coins collected.
var coins := 0
@onready var initial_position := position
@onready var gravity: Vector3 = ProjectSettings.get_setting("physics/3d/default_gravity") * \
ProjectSettings.get_setting("physics/3d/default_gravity_vector")
@onready var _camera := $Target/Camera3D as Camera3D
@onready var _animation_tree := $AnimationTree as AnimationTree
func _physics_process(delta: float) -> void:
if Input.is_action_pressed("reset_position") or global_position.y < -12:
# Player hit the reset button or fell off the map.
position = initial_position
velocity = Vector3.ZERO
# Update coin count and its "parallax" copies.
# This gives text a pseudo-3D appearance while still using Label3D instead of the more limited TextMesh.
%CoinCount.text = str(coins)
%CoinCount.get_node("Parallax").text = str(coins)
%CoinCount.get_node("Parallax2").text = str(coins)
%CoinCount.get_node("Parallax3").text = str(coins)
%CoinCount.get_node("Parallax4").text = str(coins)
velocity += gravity * delta
var anim := _Anim.FLOOR
var vertical_velocity := velocity.y
var horizontal_velocity := Vector3(velocity.x, 0, velocity.z)
var horizontal_direction := horizontal_velocity.normalized()
var horizontal_speed := horizontal_velocity.length()
# Player input.
var cam_basis := _camera.get_global_transform().basis
var movement_vec2 := Input.get_vector(&"move_left", &"move_right", &"move_forward", &"move_back")
var movement_direction := cam_basis * Vector3(movement_vec2.x, 0, movement_vec2.y)
movement_direction.y = 0
movement_direction = movement_direction.normalized()
var jump_attempt := Input.is_action_pressed(&"jump")
var shoot_attempt := Input.is_action_pressed(&"shoot")
if is_on_floor():
var sharp_turn := horizontal_speed > 0.1 and \
acos(movement_direction.dot(horizontal_direction)) > SHARP_TURN_THRESHOLD
if movement_direction.length() > 0.1 and not sharp_turn:
if horizontal_speed > 0.001:
horizontal_direction = adjust_facing(
horizontal_direction,
movement_direction,
delta,
1.0 / horizontal_speed * TURN_SPEED,
Vector3.UP
)
else:
horizontal_direction = movement_direction
if horizontal_speed < MAX_SPEED:
horizontal_speed += ACCEL * delta
else:
horizontal_speed -= DEACCEL * delta
if horizontal_speed < 0:
horizontal_speed = 0
horizontal_velocity = horizontal_direction * horizontal_speed
var mesh_xform := ($Player/Skeleton as Node3D).get_transform()
var facing_mesh := -mesh_xform.basis[0].normalized()
facing_mesh = (facing_mesh - Vector3.UP * facing_mesh.dot(Vector3.UP)).normalized()
if horizontal_speed > 0:
facing_mesh = adjust_facing(
facing_mesh,
movement_direction,
delta,
1.0 / horizontal_speed * TURN_SPEED,
Vector3.UP
)
var m3 := Basis(
-facing_mesh,
Vector3.UP,
-facing_mesh.cross(Vector3.UP).normalized()
).scaled(CHAR_SCALE)
$Player/Skeleton.set_transform(Transform3D(m3, mesh_xform.origin))
if not jumping and jump_attempt:
vertical_velocity = JUMP_VELOCITY
jumping = true
$SoundJump.play()
else:
anim = _Anim.AIR
if movement_direction.length() > 0.1:
horizontal_velocity += movement_direction * (ACCEL * AIR_ACCEL_FACTOR * delta)
if horizontal_velocity.length() > MAX_SPEED:
horizontal_velocity = horizontal_velocity.normalized() * MAX_SPEED
elif AIR_IDLE_DEACCEL:
horizontal_speed = horizontal_speed - (DEACCEL * AIR_ACCEL_FACTOR * delta)
if horizontal_speed < 0:
horizontal_speed = 0
horizontal_velocity = horizontal_direction * horizontal_speed
if Input.is_action_just_released("jump") and velocity.y > 0.0:
# Reduce jump height if releasing the jump key before reaching the apex.
vertical_velocity *= 0.7
if jumping and vertical_velocity < 0:
jumping = false
velocity = horizontal_velocity + Vector3.UP * vertical_velocity
if is_on_floor():
movement_dir = velocity
move_and_slide()
if shoot_blend > 0:
shoot_blend *= 0.97
if (shoot_blend < 0):
shoot_blend = 0
if shoot_attempt and not prev_shoot:
shoot_blend = SHOOT_TIME
var bullet := preload("res://player/bullet/bullet.tscn").instantiate() as Bullet
bullet.set_transform($Player/Skeleton/Bullet.get_global_transform().orthonormalized())
get_parent().add_child(bullet)
bullet.set_linear_velocity(
$Player/Skeleton/Bullet.get_global_transform().basis[2].normalized() * BULLET_SPEED
)
bullet.add_collision_exception_with(self)
$SoundShoot.play()
prev_shoot = shoot_attempt
if is_on_floor():
# How much the player should be blending between the "idle" and "walk/run" animations.
_animation_tree[&"parameters/run/blend_amount"] = horizontal_speed / MAX_SPEED
# How much the player should be running (as opposed to walking). 0.0 = fully walking, 1.0 = fully running.
_animation_tree[&"parameters/speed/blend_amount"] = minf(1.0, horizontal_speed / (MAX_SPEED * 0.5))
_animation_tree[&"parameters/state/blend_amount"] = anim
_animation_tree[&"parameters/air_dir/blend_amount"] = clampf(-velocity.y / 4 + 0.5, 0, 1)
_animation_tree[&"parameters/gun/blend_amount"] = minf(shoot_blend, 1.0)
func adjust_facing(facing: Vector3, target: Vector3, step: float, adjust_rate: float, \
current_gn: Vector3) -> Vector3:
var normal := target
var t := normal.cross(current_gn).normalized()
var x := normal.dot(facing)
var y := t.dot(facing)
var ang := atan2(y,x)
if absf(ang) < 0.001:
return facing
var s := signf(ang)
ang = ang * s
var turn := ang * adjust_rate * step
var a: float
if ang < turn:
a = ang
else:
a = turn
ang = (ang - a) * s
return (normal * cos(ang) + t * sin(ang)) * facing.length()
| |
117588
|
extends Camera3D
const MAX_HEIGHT = 2.0
const MIN_HEIGHT = 0.0
var collision_exception: Array[RID] = []
@export var min_distance := 0.5
@export var max_distance := 3.5
@export var angle_v_adjust := 0.0
@export var autoturn_ray_aperture := 25.0
@export var autoturn_speed := 50.0
func _ready() -> void:
# Find collision exceptions for ray.
var node: Node = self
while is_instance_valid(node):
if node is RigidBody3D:
collision_exception.append(node.get_rid())
break
else:
node = node.get_parent()
set_physics_process(true)
# This detaches the camera transform from the parent spatial node.
set_as_top_level(true)
func _physics_process(delta: float) -> void:
var target := (get_parent() as Node3D).get_global_transform().origin
var pos := get_global_transform().origin
var difference := pos - target
# Regular delta follow.
# Check ranges.
if difference.length() < min_distance:
difference = difference.normalized() * min_distance
elif difference.length() > max_distance:
difference = difference.normalized() * max_distance
# Check upper and lower height.
difference.y = clamp(difference.y, MIN_HEIGHT, MAX_HEIGHT)
# Check autoturn.
var ds := PhysicsServer3D.space_get_direct_state(get_world_3d().get_space())
var col_left := ds.intersect_ray(PhysicsRayQueryParameters3D.create(
target,
target + Basis(Vector3.UP, deg_to_rad(autoturn_ray_aperture)) * (difference),
0xffffffff,
collision_exception
))
var col := ds.intersect_ray(PhysicsRayQueryParameters3D.create(
target,
target + difference,
0xffffffff,
collision_exception
))
var col_right := ds.intersect_ray(PhysicsRayQueryParameters3D.create(
target,
target + Basis(Vector3.UP, deg_to_rad(-autoturn_ray_aperture)) * (difference),
0xffffffff,
collision_exception
))
if not col.is_empty():
# If main ray was occluded, get camera closer, this is the worst case scenario.
difference = col.position - target
elif not col_left.is_empty() and col_right.is_empty():
# If only left ray is occluded, turn the camera around to the right.
difference = Basis(Vector3.UP, deg_to_rad(-delta * (autoturn_speed))) * difference
elif col_left.is_empty() and not col_right.is_empty():
# If only right ray is occluded, turn the camera around to the left.
difference = Basis(Vector3.UP, deg_to_rad(delta * autoturn_speed)) * difference
# Do nothing otherwise, left and right are occluded but center is not, so do not autoturn.
# Apply lookat.
if difference.is_zero_approx():
difference = (pos - target).normalized() * 0.0001
pos = target + difference
look_at_from_position(pos, target, Vector3.UP)
# Turn a little up or down.
transform.basis = Basis(transform.basis[0], deg_to_rad(angle_v_adjust)) * transform.basis
| |
117614
|
extends VBoxContainer
func _ready() -> void:
get_viewport().size_changed.connect(_on_viewport_size_changed)
_on_viewport_size_changed()
func _process(_delta: float) -> void:
$FPS.text = "%d FPS (%.2f mspf)" % [Engine.get_frames_per_second(), 1000.0 / Engine.get_frames_per_second()]
func _on_viewport_size_changed() -> void:
$Resolution.text = "%s × %s" % [get_viewport().size.x, get_viewport().size.y]
| |
117619
|
extends Node
const ROT_SPEED = 0.003
const ZOOM_SPEED = 0.125
const MAIN_BUTTONS = MOUSE_BUTTON_MASK_LEFT | MOUSE_BUTTON_MASK_RIGHT | MOUSE_BUTTON_MASK_MIDDLE
var tester_index := 0
var rot_x := -TAU / 16 # This must be kept in sync with RotationX.
var rot_y := TAU / 8 # This must be kept in sync with CameraHolder.
var camera_distance := 4.0
var base_height := int(ProjectSettings.get_setting("display/window/size/viewport_height"))
@onready var testers: Node3D = $Testers
@onready var camera_holder: Node3D = $CameraHolder # Has a position and rotates on Y.
@onready var rotation_x: Node3D = $CameraHolder/RotationX
@onready var camera: Camera3D = $CameraHolder/RotationX/Camera3D
func _ready() -> void:
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
update_gui()
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed(&"ui_left"):
_on_previous_pressed()
if event.is_action_pressed(&"ui_right"):
_on_next_pressed()
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
camera_distance -= ZOOM_SPEED
if event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
camera_distance += ZOOM_SPEED
camera_distance = clamp(camera_distance, 1.5, 6)
if event is InputEventMouseMotion and event.button_mask & MAIN_BUTTONS:
# Compensate motion speed to be resolution-independent (based on the window height).
var relative_motion: Vector2 = event.relative * DisplayServer.window_get_size().y / base_height
rot_y -= relative_motion.x * ROT_SPEED
rot_x -= relative_motion.y * ROT_SPEED
rot_x = clamp(rot_x, -1.57, 0)
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
func _process(delta: float) -> void:
var current_tester: Node3D = testers.get_child(tester_index)
# This code assumes CameraHolder's X and Y coordinates are already correct.
var current_position := camera_holder.global_transform.origin.z
var target_position := current_tester.global_transform.origin.z
camera_holder.global_transform.origin.z = lerpf(current_position, target_position, 3 * delta)
camera.position.z = lerpf(camera.position.z, camera_distance, 10 * delta)
func _on_previous_pressed() -> void:
tester_index = max(0, tester_index - 1)
update_gui()
func _on_next_pressed() -> void:
tester_index = min(tester_index + 1, testers.get_child_count() - 1)
update_gui()
func update_gui() -> void:
$TestName.text = str(testers.get_child(tester_index).name).capitalize()
$Previous.disabled = tester_index == 0
$Next.disabled = tester_index == testers.get_child_count() - 1
| |
117632
|
# 3D Labels and Texts
This project showcases the two main 3D text techniques supported by Godot:
Label3D and TextMesh.
Both Label3D and TextMesh exist in 3D space and can optionally be occluded by
other objects, but they serve different use cases.
**Label3D:** The Label3D node is a 3D node like any other. It draws text using
one quad per character, which can optionally be set to work as a billboard.
**TextMesh:** Unlike Label3D, TextMesh can optionally have actual depth since it
generates geometry to represent the text. TextMesh is not a node, but a
PrimitiveMesh resource you use within a MeshsInstance3D node. Therefore, you
won't see TextMesh in the Create New Node dialog.
Icons can also be displayed in Label3D and TextMesh using icon fonts, which can
be generated from SVG files using serivces like
[Fontello](https://fontello.com/). Note that while Label3D supports colored
rasterized fonts (such as emoji), only monochrome fonts can be generated from
Fontello. TextMesh and Label3D with MSDF fonts are limited to monochrome fonts
too.
Both standard rasterized and MSDF fonts can be used in Label3D, while TextMesh
will only support fonts that can be drawn as MSDF well. This excludes fonts that
have self-intersecting outlines, which Godot currently doesn't handle well when
converting them to MSDF.
In most scenarios, Label3D is easier to use and can look better (thanks to
outlines and MSDF rendering). TextMesh is more powerful and is intended for more
specialized use cases.
Language: GDScript
Renderer: Forward+
Check out this demo on the asset library: https://godotengine.org/asset-library/asset/2740
## Screenshots

| |
117640
|
extends Node
const ROT_SPEED = 0.003
const ZOOM_SPEED = 0.125
const MAIN_BUTTONS = MOUSE_BUTTON_MASK_LEFT | MOUSE_BUTTON_MASK_RIGHT | MOUSE_BUTTON_MASK_MIDDLE
var tester_index := 0
var rot_x := -TAU / 16 # This must be kept in sync with RotationX.
var rot_y := TAU / 8 # This must be kept in sync with CameraHolder.
var camera_distance := 2.0
var base_height: = int(ProjectSettings.get_setting("display/window/size/viewport_height"))
@onready var testers: Node3D = $Testers
@onready var camera_holder: Node3D = $CameraHolder # Has a position and rotates on Y.
@onready var rotation_x: Node3D = $CameraHolder/RotationX
@onready var camera: Camera3D = $CameraHolder/RotationX/Camera3D
func _ready() -> void:
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
update_gui()
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed(&"ui_left"):
_on_previous_pressed()
if event.is_action_pressed(&"ui_right"):
_on_next_pressed()
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
camera_distance -= ZOOM_SPEED
if event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
camera_distance += ZOOM_SPEED
camera_distance = clamp(camera_distance, 1.5, 6)
if event is InputEventMouseMotion and event.button_mask & MAIN_BUTTONS:
# Compensate motion speed to be resolution-independent (based on the window height).
var relative_motion: Vector2 = event.relative * DisplayServer.window_get_size().y / base_height
rot_y -= relative_motion.x * ROT_SPEED
rot_x -= relative_motion.y * ROT_SPEED
rot_x = clamp(rot_x, -1.57, 0)
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
func _process(delta: float) -> void:
var current_tester: Node3D = testers.get_child(tester_index)
# This code assumes CameraHolder's X and Y coordinates are already correct.
var current_position := camera_holder.global_transform.origin.z
var target_position := current_tester.global_transform.origin.z
camera_holder.global_transform.origin.z = lerpf(current_position, target_position, 3 * delta)
camera.position.z = lerpf(camera.position.z, camera_distance, 10 * delta)
func _on_previous_pressed() -> void:
tester_index = max(0, tester_index - 1)
update_gui()
func _on_next_pressed() -> void:
tester_index = min(tester_index + 1, testers.get_child_count() - 1)
update_gui()
func update_gui() -> void:
$TestName.text = str(testers.get_child(tester_index).name).capitalize()
$Previous.disabled = tester_index == 0
$Next.disabled = tester_index == testers.get_child_count() - 1
# Only display player name field if relevant.
$Testers/Label3DHealthBar/Name2.visible = str(testers.get_child(tester_index).name) == "Label3DHealthBar"
$Testers/Label3DHealthBar/LineEdit.visible = str(testers.get_child(tester_index).name) == "Label3DHealthBar"
func _on_line_edit_text_submitted(_new_text: String) -> void:
$Testers/Label3DHealthBar/LineEdit.release_focus()
| |
117651
|
extends Control
# Window project settings:
# - Stretch mode is set to `canvas_items` (`2d` in Godot 3.x)
# - Stretch aspect is set to `expand`
@onready var world_environment := $WorldEnvironment
@onready var directional_light := $Node3D/DirectionalLight3D
@onready var camera := $Node3D/Camera3D
@onready var fps_label := $FPSLabel
@onready var resolution_label := $ResolutionLabel
var counter := 0.0
# When the screen changes size, we need to update the 3D
# viewport quality setting. If we don't do this, the viewport will take
# the size from the main viewport.
var viewport_start_size := Vector2(
ProjectSettings.get_setting(&"display/window/size/viewport_width"),
ProjectSettings.get_setting(&"display/window/size/viewport_height")
)
func _ready() -> void:
get_viewport().size_changed.connect(update_resolution_label)
update_resolution_label()
# Disable V-Sync to uncap framerate on supported platforms. This makes performance comparison
# easier on high-end machines that easily reach the monitor's refresh rate.
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
func _process(delta: float) -> void:
counter += delta
# Hide FPS label until it's initially updated by the engine (this can take up to 1 second).
fps_label.visible = counter >= 1.0
fps_label.text = "%d FPS (%.2f mspf)" % [Engine.get_frames_per_second(), 1000.0 / Engine.get_frames_per_second()]
# Color FPS counter depending on framerate.
# The Gradient resource is stored as metadata within the FPSLabel node (accessible in the inspector).
fps_label.modulate = fps_label.get_meta("gradient").sample(remap(Engine.get_frames_per_second(), 0, 180, 0.0, 1.0))
func update_resolution_label() -> void:
var viewport_render_size = get_viewport().size * get_viewport().scaling_3d_scale
resolution_label.text = "3D viewport resolution: %d × %d (%d%%)" \
% [viewport_render_size.x, viewport_render_size.y, round(get_viewport().scaling_3d_scale * 100)]
func _on_HideShowButton_toggled(show_settings: bool) -> void:
# Option to hide the settings so you can see the changes to the 3d world better.
var button := $HideShowButton
var settings_menu := $SettingsMenu
if show_settings:
button.text = "Hide settings"
else:
button.text = "Show settings"
settings_menu.visible = show_settings
# Video settings.
func _on_ui_scale_option_button_item_selected(index: int) -> void:
# For changing the UI, we take the viewport size, which we set in the project settings.
var new_size := viewport_start_size
if index == 0: # Smaller (66%)
new_size *= 1.5
elif index == 1: # Small (80%)
new_size *= 1.25
elif index == 2: # Medium (100%) (default)
new_size *= 1.0
elif index == 3: # Large (133%)
new_size *= 0.75
elif index == 4: # Larger (200%)
new_size *= 0.5
get_tree().root.set_content_scale_size(new_size)
func _on_quality_slider_value_changed(value: float) -> void:
get_viewport().scaling_3d_scale = value
update_resolution_label()
func _on_filter_option_button_item_selected(index: int) -> void:
# Viewport scale mode setting.
if index == 0: # Bilinear (Fastest)
get_viewport().scaling_3d_mode = Viewport.SCALING_3D_MODE_BILINEAR
# FSR Sharpness is only effective when the scaling mode is FSR 1.0 or 2.2.
%FSRSharpnessLabel.visible = false
%FSRSharpnessSlider.visible = false
elif index == 1: # FSR 1.0 (Fast)
get_viewport().scaling_3d_mode = Viewport.SCALING_3D_MODE_FSR
# FSR Sharpness is only effective when the scaling mode is FSR 1.0 or 2.2.
%FSRSharpnessLabel.visible = true
%FSRSharpnessSlider.visible = true
elif index == 2: # FSR 2.2 (Fast)
get_viewport().scaling_3d_mode = Viewport.SCALING_3D_MODE_FSR2
# FSR Sharpness is only effective when the scaling mode is FSR 1.0 or 2.2.
%FSRSharpnessLabel.visible = true
%FSRSharpnessSlider.visible = true
func _on_fsr_sharpness_slider_value_changed(value: float) -> void:
# Lower FSR sharpness values result in a sharper image.
# Invert the slider so that higher values result in a sharper image,
# which is generally expected from users.
get_viewport().fsr_sharpness = 2.0 - value
func _on_vsync_option_button_item_selected(index: int) -> void:
# Vsync is enabled by default.
# Vertical synchronization locks framerate and makes screen tearing not visible at the cost of
# higher input latency and stuttering when the framerate target is not met.
# Adaptive V-Sync automatically disables V-Sync when the framerate target is not met, and enables
# V-Sync otherwise. This prevents suttering and reduces input latency when the framerate target
# is not met, at the cost of visible tearing.
if index == 0: # Disabled (default)
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
elif index == 1: # Adaptive
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ADAPTIVE)
elif index == 2: # Enabled
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED)
func _on_limit_fps_slider_value_changed(value: float):
# The maximum number of frames per second that can be rendered.
# A value of 0 means "no limit".
Engine.max_fps = value
func _on_msaa_option_button_item_selected(index: int) -> void:
# Multi-sample anti-aliasing. High quality, but slow. It also does not smooth out the edges of
# transparent (alpha scissor) textures.
if index == 0: # Disabled (default)
get_viewport().msaa_3d = Viewport.MSAA_DISABLED
elif index == 1: # 2×
get_viewport().msaa_3d = Viewport.MSAA_2X
elif index == 2: # 4×
get_viewport().msaa_3d = Viewport.MSAA_4X
elif index == 3: # 8×
get_viewport().msaa_3d = Viewport.MSAA_8X
func _on_taa_option_button_item_selected(index: int) -> void:
# Temporal antialiasing. Smooths out everything including specular aliasing, but can introduce
# ghosting artifacts and blurring in motion. Moderate performance cost.
get_viewport().use_taa = index == 1
func _on_fxaa_option_button_item_selected(index: int) -> void:
# Fast approximate anti-aliasing. Much faster than MSAA (and works on alpha scissor edges),
# but blurs the whole scene rendering slightly.
get_viewport().screen_space_aa = int(index == 1) as Viewport.ScreenSpaceAA
func _on_fullscreen_option_button_item_selected(index: int) -> void:
# To change between winow, fullscreen and other window modes,
# set the root mode to one of the options of Window.MODE_*.
# Other modes are maximized and minimized.
if index == 0: # Disabled (default)
get_tree().root.set_mode(Window.MODE_WINDOWED)
elif index == 1: # Fullscreen
get_tree().root.set_mode(Window.MODE_FULLSCREEN)
elif index == 2: # Exclusive Fullscreen
get_tree().root.set_mode(Window.MODE_EXCLUSIVE_FULLSCREEN)
func _on_fov_slider_value_changed(value: float) -> void:
camera.fov = value
# Quality settings.
fu
| |
117675
|
extends Camera3D
const MOUSE_SENSITIVITY = 0.002
const MOVE_SPEED = 1.5
var rot := Vector3()
var velocity := Vector3()
func _ready() -> void:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _input(event: InputEvent) -> void:
# Mouse look (only if the mouse is captured).
if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
# Horizontal mouse look.
rot.y -= event.relative.x * MOUSE_SENSITIVITY
# Vertical mouse look.
rot.x = clamp(rot.x - event.relative.y * MOUSE_SENSITIVITY, -1.57, 1.57)
transform.basis = Basis.from_euler(rot)
if event.is_action_pressed("toggle_mouse_capture"):
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
else:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _process(delta: float) -> void:
var motion := Vector3(
Input.get_axis(&"move_left", &"move_right"),
0,
Input.get_axis(&"move_forward", &"move_back")
)
# Normalize motion to prevent diagonal movement from being
# `sqrt(2)` times faster than straight movement.
motion = motion.normalized()
velocity += MOVE_SPEED * delta * (transform.basis * motion)
velocity *= 0.85
position += velocity
| |
117697
|
# This acts as a staging scene shown until the main scene is fully loaded.
extends Control
func _ready() -> void:
for i in 2:
# Wait 2 frames before starting to change to the main scene,
# so that the loading text can be shown instead of the splash screen.
await get_tree().process_frame
# Do not use `preload()` to avoid incurring the loading time before the
# loading text can be shown.
get_tree().change_scene_to_packed(load("res://test.tscn"))
| |
117715
|
# This script creates the ImageTexture and assigns it to an existing material at runtime.
# By not having `@tool`, this avoids saving the raw image data in the scene file,
# which would make it much larger.
extends MeshInstance3D
const TEXTURE_SIZE = Vector2i(512, 512)
const GRID_SIZE = 32
const GRID_THICKNESS = 4
func _ready() -> void:
var image := Image.create(TEXTURE_SIZE.x, TEXTURE_SIZE.y, false, Image.FORMAT_RGB8)
# Use 1-dimensional loop as it's faster than a nested loop.
for i in TEXTURE_SIZE.x * TEXTURE_SIZE.y:
var x := i % TEXTURE_SIZE.y
var y := i / TEXTURE_SIZE.y
var color := Color()
# Draw a grid with more contrasted points where X and Y lines meet.
# Center the grid's lines so that lines are visible on all the texture's edges.
if (x + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS and (y + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS:
color.g = 0.8
elif (x + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS or (y + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS:
color.g = 0.25
# Add some random noise for detail.
color += Color(randf(), randf(), randf()) * 0.1
image.set_pixel(x, y, color)
image.generate_mipmaps()
var image_texture := ImageTexture.create_from_image(image)
get_surface_override_material(0).albedo_texture = image_texture
image.bump_map_to_normal_map(5.0)
image.generate_mipmaps()
var image_texture_normal := ImageTexture.create_from_image(image)
get_surface_override_material(0).normal_texture = image_texture_normal
| |
117718
|
extends Camera3D
const MOUSE_SENSITIVITY = 0.002
const MOVE_SPEED = 0.65
var rot := Vector3()
var velocity := Vector3()
func _ready() -> void:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _input(event: InputEvent) -> void:
# Mouse look (only if the mouse is captured).
if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
# Horizontal mouse look.
rot.y -= event.relative.x * MOUSE_SENSITIVITY
# Vertical mouse look.
rot.x = clamp(rot.x - event.relative.y * MOUSE_SENSITIVITY, -1.57, 1.57)
transform.basis = Basis.from_euler(rot)
if event.is_action_pressed(&"toggle_mouse_capture"):
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
else:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _process(delta: float) -> void:
var motion := Vector3(
Input.get_axis(&"move_left", &"move_right"),
0,
Input.get_axis(&"move_forward", &"move_back")
)
# Normalize motion to prevent diagonal movement from being
# `sqrt(2)` times faster than straight movement.
motion = motion.normalized()
velocity += MOVE_SPEED * delta * (transform.basis * motion)
velocity *= 0.85
position += velocity
| |
117743
|
[gd_scene load_steps=3 format=3 uid="uid://3gkujifjokqw"]
[sub_resource type="PlaneMesh" id="1"]
[sub_resource type="ConcavePolygonShape3D" id="2"]
data = PackedVector3Array(-1, 0, 1, 1, 0, -1, 1, 0, 1, -1, 0, 1, -1, 0, -1, 1, 0, -1)
[node name="StaticBodyPlane" type="StaticBody3D"]
[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
transform = Transform3D(50, 0, 0, 0, 1, 0, 0, 0, 50, 0, 0, 0)
mesh = SubResource( "1" )
[node name="CollisionShape" type="CollisionShape3D" parent="."]
transform = Transform3D(50, 0, 0, 0, 1, 0, 0, 0, 50, 0, 0, 0)
shape = SubResource( "2" )
| |
117744
|
[gd_scene load_steps=4 format=3 uid="uid://cl2vpuxqgnylc"]
[ext_resource type="Shape3D" path="res://assets/robot_head/godot3_robot_head_collision.tres" id="1"]
[ext_resource type="ArrayMesh" path="res://assets/robot_head/godot3_robot_head.mesh" id="2"]
[ext_resource type="PackedScene" uid="uid://3gkujifjokqw" path="res://tests/static_scene_plane.tscn" id="3"]
[node name="StaticScene" type="Node3D"]
[node name="StaticBodyPlane" parent="." instance=ExtResource( "3" )]
[node name="StaticBodyHead" type="StaticBody3D" parent="."]
transform = Transform3D(10, 0, 0, 0, 8.66025, 5, 0, -5, 8.66025, 0, -11.1389, 2.29332)
[node name="RobotHead" type="MeshInstance3D" parent="StaticBodyHead"]
mesh = ExtResource( "2" )
[node name="CollisionShape" type="CollisionShape3D" parent="StaticBodyHead"]
shape = ExtResource( "1" )
| |
117755
|
extends Test
const OPTION_TEST_CASE_HIT_FROM_INSIDE = "Test case/Hit from inside"
var _hit_from_inside := false
var _do_raycasts := false
@onready var _raycast_visuals := ImmediateMesh.new()
@onready var _material := StandardMaterial3D.new()
func _ready() -> void:
var options: OptionMenu = $Options
options.add_menu_item(OPTION_TEST_CASE_HIT_FROM_INSIDE, true, false)
options.option_changed.connect(_on_option_changed)
_material.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
_material.vertex_color_use_as_albedo = true
var raycast_mesh_instance := MeshInstance3D.new()
raycast_mesh_instance.mesh = _raycast_visuals
add_child(raycast_mesh_instance)
move_child(raycast_mesh_instance, get_child_count())
await start_timer(0.5).timeout
if is_timer_canceled():
return
_do_raycasts = true
func _physics_process(delta: float) -> void:
super._physics_process(delta)
if not _do_raycasts:
return
_do_raycasts = false
Log.print_log("* Start Raycasting...")
_raycast_visuals.clear_surfaces()
_raycast_visuals.surface_begin(Mesh.PRIMITIVE_LINES)
for shape in $Shapes.get_children():
var body: PhysicsBody3D = shape
var space_state := body.get_world_3d().direct_space_state
Log.print_log("* Testing: %s" % body.name)
var center := body.global_transform.origin
# Raycast entering from the top.
var res := _add_raycast(space_state, center + Vector3(0.0, 2.0, 0.0), center)
Log.print_log("Raycast in: %s" % ("HIT" if res else "NO HIT"))
# Raycast exiting from inside.
center.x -= 0.2
res = _add_raycast(space_state, center, center - Vector3(0.0, 3.0, 0.0))
Log.print_log("Raycast out: %s" % ("HIT" if res else "NO HIT"))
# Raycast all inside.
center.x += 0.4
res = _add_raycast(space_state, center, center - Vector3(0.0, 0.8, 0.0))
Log.print_log("Raycast inside: %s" % ("HIT" if res else "NO HIT"))
_raycast_visuals.surface_end()
_raycast_visuals.surface_set_material(0, _material)
func _on_option_changed(option: String, checked: bool) -> void:
match option:
OPTION_TEST_CASE_HIT_FROM_INSIDE:
_hit_from_inside = checked
_do_raycasts = true
func _add_raycast(space_state: PhysicsDirectSpaceState3D, pos_start: Vector3, pos_end: Vector3) -> Dictionary:
var params := PhysicsRayQueryParameters3D.new()
params.from = pos_start
params.to = pos_end
params.hit_from_inside = _hit_from_inside
var result := space_state.intersect_ray(params)
if result:
_raycast_visuals.surface_set_color(Color.GREEN)
else:
_raycast_visuals.surface_set_color(Color.RED.darkened(0.5))
# Draw raycast line.
_raycast_visuals.surface_add_vertex(pos_start)
_raycast_visuals.surface_add_vertex(pos_end)
# Draw raycast arrow.
_raycast_visuals.surface_add_vertex(pos_end)
_raycast_visuals.surface_add_vertex(pos_end + Vector3(-0.05, 0.1, 0.0))
_raycast_visuals.surface_add_vertex(pos_end)
_raycast_visuals.surface_add_vertex(pos_end + Vector3(0.05, 0.1, 0.0))
return result
| |
117757
|
[gd_scene load_steps=28 format=3 uid="uid://se7gyhmygqul"]
[ext_resource type="Script" path="res://utils/rigidbody_ground_check.gd" id="1"]
[ext_resource type="PackedScene" uid="uid://b1ihqm3x8jru" path="res://tests/test_options.tscn" id="2"]
[ext_resource type="Script" path="res://tests/functional/test_rigidbody_ground_check.gd" id="3"]
[ext_resource type="Script" path="res://utils/camera_orbit.gd" id="4"]
[sub_resource type="PhysicsMaterial" id="1"]
friction = 0.0
[sub_resource type="BoxShape3D" id="2"]
[sub_resource type="BoxMesh" id="3"]
[sub_resource type="PhysicsMaterial" id="5"]
friction = 0.0
[sub_resource type="CapsuleShape3D" id="6"]
[sub_resource type="CapsuleMesh" id="7"]
[sub_resource type="PhysicsMaterial" id="9"]
friction = 0.0
[sub_resource type="CylinderShape3D" id="10"]
[sub_resource type="CylinderMesh" id="11"]
[sub_resource type="PhysicsMaterial" id="13"]
friction = 0.0
[sub_resource type="ConvexPolygonShape3D" id="14"]
points = PackedVector3Array(-0.7, 0, -0.7, -0.3, 0, 0.8, 0.8, 0, -0.3, 0, -1, 0)
[sub_resource type="ArrayMesh" id="15"]
_surfaces = [{
"aabb": AABB(-0.7, -1, -0.7, 1.5, 1.00001, 1.5),
"format": 34359742467,
"index_count": 12,
"index_data": PackedByteArray(0, 0, 1, 0, 3, 0, 1, 0, 2, 0, 3, 0, 2, 0, 0, 0, 3, 0, 2, 0, 1, 0, 0, 0),
"primitive": 3,
"uv_scale": Vector4(0, 0, 0, 0),
"vertex_count": 4,
"vertex_data": PackedByteArray(51, 51, 51, 191, 0, 0, 0, 0, 51, 51, 51, 191, 154, 153, 153, 190, 0, 0, 0, 0, 205, 204, 76, 63, 205, 204, 76, 63, 0, 0, 0, 0, 154, 153, 153, 190, 0, 0, 0, 0, 0, 0, 128, 191, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 59, 182, 3, 0, 0, 0, 0, 0, 0)
}]
[sub_resource type="PhysicsMaterial" id="17"]
friction = 0.0
[sub_resource type="SphereShape3D" id="18"]
[sub_resource type="SphereMesh" id="19"]
[sub_resource type="PlaneMesh" id="23"]
size = Vector2(50, 20)
[sub_resource type="ConvexPolygonShape3D" id="24"]
points = PackedVector3Array(25, 0, 10, -25, 0, 10, 25, 0, -10, -25, 0, -10)
[sub_resource type="ConvexPolygonShape3D" id="25"]
points = PackedVector3Array(25, 0, 10, -25, 0, 10, 25, 0, -10, -25, 0, -10)
[sub_resource type="ConvexPolygonShape3D" id="26"]
points = PackedVector3Array(50, 0, 50, -50, 0, 50, 50, 0, -50, -50, 0, -50)
[sub_resource type="ConcavePolygonShape3D" id="27"]
data = PackedVector3Array(-1, 0, 1, 1, 0, -1, 1, 0, 1, -1, 0, 1, -1, 0, -1, 1, 0, -1)
[sub_resource type="ConcavePolygonShape3D" id="28"]
data = PackedVector3Array(50, 0, 50, -50, 0, 50, 50, 0, -50, -50, 0, 50, -50, 0, -50, 50, 0, -50)
[sub_resource type="BoxShape3D" id="29"]
size = Vector3(100, 2, 40)
[sub_resource type="BoxShape3D" id="30"]
size = Vector3(200, 2, 200)
[node name="Test" type="Node3D"]
script = ExtResource("3")
[node name="LabelBodyType" type="Label" parent="."]
offset_left = 14.0
offset_top = 62.0
offset_right = 171.0
offset_bottom = 85.0
text = "Floor Type: "
[node name="Options" parent="." instance=ExtResource("2")]
offset_top = 120.0
offset_bottom = 140.0
focus_mode = 2
[node name="DynamicShapes" type="Node3D" parent="."]
[node name="Bodies" type="Node3D" parent="DynamicShapes"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 5.2912, 0)
[node name="RigidBodyBox" type="RigidBody3D" parent="DynamicShapes/Bodies"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6, 0, 0)
axis_lock_angular_x = true
axis_lock_angular_y = true
axis_lock_angular_z = true
physics_material_override = SubResource("1")
script = ExtResource("1")
[node name="CollisionShape" type="CollisionShape3D" parent="DynamicShapes/Bodies/RigidBodyBox"]
transform = Transform3D(0.6, 0, 0, 0, 1, 0, 0, 0, 0.6, 0, 0, 0)
shape = SubResource("2")
[node name="MeshInstance3D" type="MeshInstance3D" parent="DynamicShapes/Bodies/RigidBodyBox/CollisionShape"]
mesh = SubResource("3")
[node name="RigidBodyCapsule" type="RigidBody3D" parent="DynamicShapes/Bodies"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -3, 0, 0)
axis_lock_angular_x = true
axis_lock_angular_y = true
axis_lock_angular_z = true
physics_material_override = SubResource("5")
script = ExtResource("1")
[node name="CollisionShape" type="CollisionShape3D" parent="DynamicShapes/Bodies/RigidBodyCapsule"]
transform = Transform3D(0.8, 0, 0, 0, 0.8, 0, 0, 0, 0.8, 0, 0, 0)
shape = SubResource("6")
[node name="MeshInstance3D" type="MeshInstance3D" parent="DynamicShapes/Bodies/RigidBodyCapsule/CollisionShape"]
mesh = SubResource("7")
[node name="RigidBodyCylinder" type="RigidBody3D" parent="DynamicShapes/Bodies"]
axis_lock_angular_x = true
axis_lock_angular_y = true
axis_lock_angular_z = true
physics_material_override = SubResource("9")
script = ExtResource("1")
[node name="CollisionShape" type="CollisionShape3D" parent="DynamicShapes/Bodies/RigidBodyCylinder"]
transform = Transform3D(0.8, 0, 0, 0, 1, 0, 0, 0, 0.8, 0, 0, 0)
shape = SubResource("10")
[node name="MeshInstance3D" type="MeshInstance3D" parent="DynamicShapes/Bodies/RigidBodyCylinder/CollisionShape"]
mesh = SubResource("11")
| |
117758
|
[node name="RigidBodyConvex" type="RigidBody3D" parent="DynamicShapes/Bodies"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 3, 0.974548, 0)
axis_lock_angular_x = true
axis_lock_angular_y = true
axis_lock_angular_z = true
physics_material_override = SubResource("13")
script = ExtResource("1")
[node name="CollisionShape" type="CollisionShape3D" parent="DynamicShapes/Bodies/RigidBodyConvex"]
transform = Transform3D(1.5, 0, 0, 0, 2, 0, 0, 0, 1.5, 0, 0, 0)
shape = SubResource("14")
[node name="MeshInstance3D" type="MeshInstance3D" parent="DynamicShapes/Bodies/RigidBodyConvex/CollisionShape"]
mesh = SubResource("15")
[node name="RigidBodySphere" type="RigidBody3D" parent="DynamicShapes/Bodies"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6, 0, 0)
axis_lock_angular_x = true
axis_lock_angular_y = true
axis_lock_angular_z = true
physics_material_override = SubResource("17")
script = ExtResource("1")
[node name="CollisionShape" type="CollisionShape3D" parent="DynamicShapes/Bodies/RigidBodySphere"]
transform = Transform3D(0.8, 0, 0, 0, 0.8, 0, 0, 0, 0.8, 0, 0, 0)
shape = SubResource("18")
[node name="MeshInstance3D" type="MeshInstance3D" parent="DynamicShapes/Bodies/RigidBodySphere/CollisionShape"]
mesh = SubResource("19")
[node name="Floors" type="Node3D" parent="."]
[node name="ConvexSmall" type="Node3D" parent="Floors"]
[node name="ConvexFloor" type="StaticBody3D" parent="Floors/ConvexSmall"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -10)
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/ConvexSmall/ConvexFloor"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/ConvexSmall/ConvexFloor"]
shape = SubResource("24")
[node name="ConvexFloor2" type="StaticBody3D" parent="Floors/ConvexSmall"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 10)
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/ConvexSmall/ConvexFloor2"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/ConvexSmall/ConvexFloor2"]
shape = SubResource("25")
[node name="ConvexBig" type="Node3D" parent="Floors"]
[node name="ConvexFloor" type="StaticBody3D" parent="Floors/ConvexBig"]
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/ConvexBig/ConvexFloor"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/ConvexBig/ConvexFloor"]
shape = SubResource("26")
[node name="ConcaveSmall" type="Node3D" parent="Floors"]
[node name="ConcaveFloor" type="StaticBody3D" parent="Floors/ConcaveSmall"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -10)
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/ConcaveSmall/ConcaveFloor"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/ConcaveSmall/ConcaveFloor"]
transform = Transform3D(25, 0, 0, 0, 1, 0, 0, 0, 10, 0, 0, 0)
shape = SubResource("27")
[node name="ConcaveFloor2" type="StaticBody3D" parent="Floors/ConcaveSmall"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 10)
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/ConcaveSmall/ConcaveFloor2"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/ConcaveSmall/ConcaveFloor2"]
transform = Transform3D(25, 0, 0, 0, 1, 0, 0, 0, 10, 0, 0, 0)
shape = SubResource("27")
[node name="ConcaveBig" type="Node3D" parent="Floors"]
[node name="ConcaveFloor" type="StaticBody3D" parent="Floors/ConcaveBig"]
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/ConcaveBig/ConcaveFloor"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/ConcaveBig/ConcaveFloor"]
shape = SubResource("28")
[node name="BoxSmall" type="Node3D" parent="Floors"]
[node name="BoxFloor" type="StaticBody3D" parent="Floors/BoxSmall"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -10)
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/BoxSmall/BoxFloor"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/BoxSmall/BoxFloor"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0)
shape = SubResource("29")
[node name="BoxFloor2" type="StaticBody3D" parent="Floors/BoxSmall"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 10)
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/BoxSmall/BoxFloor2"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/BoxSmall/BoxFloor2"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0)
shape = SubResource("29")
[node name="BoxBig" type="Node3D" parent="Floors"]
[node name="BoxFloor" type="StaticBody3D" parent="Floors/BoxBig"]
[node name="MeshInstance3D" type="MeshInstance3D" parent="Floors/BoxBig/BoxFloor"]
visible = false
mesh = SubResource("23")
[node name="CollisionShape" type="CollisionShape3D" parent="Floors/BoxBig/BoxFloor"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0)
shape = SubResource("30")
[node name="Camera3D" type="Camera3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 3.604, 22.124)
far = 1000.0
script = ExtResource("4")
| |
117762
|
[gd_scene load_steps=13 format=3 uid="uid://dgh5drb4q81kh"]
[ext_resource type="Script" path="res://utils/camera_orbit.gd" id="1"]
[ext_resource type="Script" path="res://tests/functional/test_moving_platform.gd" id="2"]
[ext_resource type="PackedScene" uid="uid://b1ihqm3x8jru" path="res://tests/test_options.tscn" id="3"]
[ext_resource type="Script" path="res://utils/characterbody_physics.gd" id="4"]
[sub_resource type="CapsuleShape3D" id="1"]
radius = 0.3
[sub_resource type="BoxShape3D" id="2"]
size = Vector3(0.6, 1.6, 0.6)
[sub_resource type="CylinderShape3D" id="3"]
radius = 0.3
height = 1.60005
[sub_resource type="SphereShape3D" id="4"]
radius = 0.79945
[sub_resource type="ConvexPolygonShape3D" id="5"]
points = PackedVector3Array(-0.7, 0, -0.7, -0.3, 0, 0.8, 0.8, 0, -0.3, 0, -0.8, 0)
[sub_resource type="PhysicsMaterial" id="7"]
[sub_resource type="BoxShape3D" id="8"]
size = Vector3(4, 0.4, 2)
[sub_resource type="Animation" id="9"]
length = 9.0
[node name="Test2" type="Node3D"]
script = ExtResource( "2" )
[node name="LabelBodyType" type="Label" parent="."]
offset_left = 14.0
offset_top = 78.0
offset_right = 171.0
offset_bottom = 92.0
text = "Body Type: "
__meta__ = {
"_edit_use_anchors_": false
}
[node name="Options" parent="." instance=ExtResource( "3" )]
offset_top = 153.0
offset_right = 134.0
offset_bottom = 182.0
[node name="Bodies" type="Node3D" parent="."]
[node name="CharacterBody3D" type="CharacterBody3D" parent="Bodies"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7, -4.18538, 0)
collision_layer = 2
script = ExtResource( "4" )
_stop_on_slopes = true
use_snap = true
[node name="Capsule" type="CollisionShape3D" parent="Bodies/CharacterBody3D"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "1" )
[node name="Box" type="CollisionShape3D" parent="Bodies/CharacterBody3D"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "2" )
[node name="Cylinder" type="CollisionShape3D" parent="Bodies/CharacterBody3D"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "3" )
[node name="Sphere" type="CollisionShape3D" parent="Bodies/CharacterBody3D"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "4" )
[node name="Convex" type="CollisionShape3D" parent="Bodies/CharacterBody3D"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "5" )
[node name="RigidBody" type="RigidDynamicBody3D" parent="Bodies"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7, -4.18538, 0)
collision_layer = 4
axis_lock_angular_x = true
axis_lock_angular_y = true
axis_lock_angular_z = true
physics_material_override = SubResource( "7" )
[node name="Capsule" type="CollisionShape3D" parent="Bodies/RigidBody"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "1" )
[node name="Box" type="CollisionShape3D" parent="Bodies/RigidBody"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "2" )
[node name="Cylinder" type="CollisionShape3D" parent="Bodies/RigidBody"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "3" )
[node name="Sphere" type="CollisionShape3D" parent="Bodies/RigidBody"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "4" )
[node name="Convex" type="CollisionShape3D" parent="Bodies/RigidBody"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.8, 0)
shape = SubResource( "5" )
[node name="Platforms" type="Node3D" parent="."]
[node name="MovingPlatform" type="AnimatableBody3D" parent="Platforms"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7, -4.235, 0)
[node name="CollisionShape" type="CollisionShape3D" parent="Platforms/MovingPlatform"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.2, 0)
shape = SubResource( "8" )
[node name="AnimationPlayer" type="AnimationPlayer" parent="Platforms/MovingPlatform"]
anims/Move = SubResource( "9" )
[node name="Camera3D" type="Camera3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 10)
current = true
script = ExtResource( "1" )
[node name="OmniLight" type="OmniLight3D" parent="Camera3D"]
omni_range = 50.0
| |
117775
|
extends RigidBody3D
var _dir := 1.0
var _distance := 10.0
var _walk_spd := 100.0
var _acceleration := 22.0
var _is_on_floor := false
@onready var _forward := -transform.basis.z
@onready var _collision_shape := $CollisionShape
@onready var _material: StandardMaterial3D = $CollisionShape/MeshInstance3D.get_active_material(0)
func _ready() -> void:
if not _material:
_material = StandardMaterial3D.new()
$CollisionShape/MeshInstance3D.set_surface_override_material(0, _material)
func _process(_delta: float) -> void:
if _is_on_floor:
_material.albedo_color = Color.WHITE
else:
_material.albedo_color = Color.RED
func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
var delta := state.step
var velocity := (_forward * _dir * _walk_spd * delta) + (state.linear_velocity * Vector3.UP)
state.linear_velocity = state.linear_velocity.move_toward(velocity, _acceleration * delta)
if state.transform.origin.z < -_distance:
_dir = -1
if state.transform.origin.z > _distance:
_dir = 1
ground_check()
func ground_check() -> void:
var space_state := get_world_3d().direct_space_state
var shape := PhysicsShapeQueryParameters3D.new()
shape.transform = _collision_shape.global_transform
shape.shape_rid = _collision_shape.shape.get_rid()
shape.collision_mask = 2
var result := space_state.get_rest_info(shape)
if result:
_is_on_floor = true
else:
_is_on_floor = false
| |
117783
|
extends RigidBody3D
const MOUSE_DELTA_COEFFICIENT = 0.01
const CAMERA_DISTANCE_COEFFICIENT = 0.2
var _picked := false
var _last_mouse_pos := Vector2.ZERO
var _mouse_pos := Vector2.ZERO
func _ready() -> void:
input_ray_pickable = true
func _input(event: InputEvent) -> void:
if event is InputEventMouseButton:
if not event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
_picked = false
if event is InputEventMouseMotion:
_mouse_pos = event.position
func _input_event(_camera: Camera3D, event: InputEvent, _position: Vector3, _normal: Vector3, _shape_idx: int) -> void:
if event is InputEventMouseButton:
if event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
_picked = true
_mouse_pos = event.position
_last_mouse_pos = _mouse_pos
func _physics_process(delta: float) -> void:
if _picked:
var mouse_delta := _mouse_pos - _last_mouse_pos
var world_delta := Vector3.ZERO
world_delta.x = mouse_delta.x * MOUSE_DELTA_COEFFICIENT
world_delta.y = -mouse_delta.y * MOUSE_DELTA_COEFFICIENT
var camera := get_viewport().get_camera_3d()
if camera:
var camera_basis := camera.global_transform.basis
world_delta = camera_basis * world_delta
var camera_dist := camera.global_transform.origin.distance_to(global_transform.origin)
const DEFAULT_CAMERA_FOV = 75.0
var fov_coefficient := camera.fov / DEFAULT_CAMERA_FOV
world_delta *= CAMERA_DISTANCE_COEFFICIENT * camera_dist * fov_coefficient
if freeze:
global_transform.origin += world_delta
else:
linear_velocity = world_delta / delta
_last_mouse_pos = _mouse_pos
| |
117785
|
extends Node
enum PhysicsEngine {
GODOT_PHYSICS,
OTHER,
}
var _engine := PhysicsEngine.OTHER
func _enter_tree() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
# Always enable visible collision shapes on startup
# (same as the Debug > Visible Collision Shapes option).
get_tree().debug_collisions_hint = true
var engine_string: String = ProjectSettings.get_setting("physics/3d/physics_engine")
match engine_string:
"DEFAULT":
_engine = PhysicsEngine.GODOT_PHYSICS
"GodotPhysics3D":
_engine = PhysicsEngine.GODOT_PHYSICS
_:
_engine = PhysicsEngine.OTHER
func _process(_delta: float) -> void:
if Input.is_action_just_pressed(&"toggle_full_screen"):
if DisplayServer.window_get_mode() == DisplayServer.WINDOW_MODE_FULLSCREEN:
DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)
else:
DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
if Input.is_action_just_pressed(&"toggle_debug_collision"):
var debug_collision_enabled := not _is_debug_collision_enabled()
_set_debug_collision_enabled(debug_collision_enabled)
if debug_collision_enabled:
Log.print_log("Debug Collision ON")
else:
Log.print_log("Debug Collision OFF")
if Input.is_action_just_pressed(&"toggle_pause"):
get_tree().paused = not get_tree().paused
if Input.is_action_just_pressed(&"exit"):
get_tree().quit()
func get_physics_engine() -> PhysicsEngine:
return _engine
func _set_debug_collision_enabled(enabled: bool) -> void:
get_tree().debug_collisions_hint = enabled
func _is_debug_collision_enabled() -> bool:
return get_tree().debug_collisions_hint
| |
117788
|
extends CharacterBody3D
@export var _stop_on_slopes := false
@export var use_snap := false
var _gravity := 20.0
func _physics_process(delta: float) -> void:
if is_on_floor():
floor_snap_length = 0.2
else:
velocity += Vector3.DOWN * _gravity * delta
floor_snap_length = 0.0
floor_stop_on_slope = _stop_on_slopes
move_and_slide()
| |
117870
|
extends Node3D
const Character = preload("res://character.gd")
var _cam_rotation := 0.0
@onready var _camera := $CameraBase/Camera3D as Camera3D
@onready var _robot := $RobotBase as Character
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
# Get closest point on navmesh for the current mouse cursor position.
var mouse_cursor_position: Vector2 = event.position
var camera_ray_length := 1000.0
var camera_ray_start := _camera.project_ray_origin(mouse_cursor_position)
var camera_ray_end := camera_ray_start + _camera.project_ray_normal(mouse_cursor_position) * camera_ray_length
var closest_point_on_navmesh := NavigationServer3D.map_get_closest_point_to_segment(
get_world_3d().navigation_map,
camera_ray_start,
camera_ray_end
)
_robot.set_target_position(closest_point_on_navmesh)
elif event is InputEventMouseMotion:
if event.button_mask & (MOUSE_BUTTON_MASK_MIDDLE + MOUSE_BUTTON_MASK_RIGHT):
_cam_rotation += event.relative.x * 0.005
$CameraBase.set_rotation(Vector3.UP * _cam_rotation)
| |
117925
|
extends Camera3D
const MOUSE_SENSITIVITY = 0.002
const MOVE_SPEED = 0.6
var volumetric_fog_volume_size := int(ProjectSettings.get_setting("rendering/environment/volumetric_fog/volume_size"))
var volumetric_fog_volume_depth := int(ProjectSettings.get_setting("rendering/environment/volumetric_fog/volume_depth"))
var rot := Vector3()
var velocity := Vector3()
@onready var label: Label = $Label
func _ready() -> void:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
update_label()
func _process(delta: float) -> void:
var motion := Vector3(
Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
0,
Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")
)
# Normalize motion to prevent diagonal movement from being
# `sqrt(2)` times faster than straight movement.
motion = motion.normalized()
velocity += MOVE_SPEED * delta * (transform.basis * motion)
velocity *= 0.85
position += velocity
func _input(event: InputEvent) -> void:
# Mouse look (only if the mouse is captured).
if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
# Horizontal mouse look.
rot.y -= event.relative.x * MOUSE_SENSITIVITY
# Vertical mouse look.
rot.x = clamp(rot.x - event.relative.y * MOUSE_SENSITIVITY, -1.57, 1.57)
transform.basis = Basis.from_euler(rot)
if event.is_action_pressed("toggle_mouse_capture"):
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
else:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
if event.is_action_pressed("toggle_temporal_reprojection"):
get_world_3d().environment.volumetric_fog_temporal_reprojection_enabled = not get_world_3d().environment.volumetric_fog_temporal_reprojection_enabled
update_label()
elif event.is_action_pressed("increase_temporal_reprojection"):
get_world_3d().environment.volumetric_fog_temporal_reprojection_amount = clamp(get_world_3d().environment.volumetric_fog_temporal_reprojection_amount + 0.01, 0.5, 0.99)
update_label()
elif event.is_action_pressed("decrease_temporal_reprojection"):
get_world_3d().environment.volumetric_fog_temporal_reprojection_amount = clamp(get_world_3d().environment.volumetric_fog_temporal_reprojection_amount - 0.01, 0.5, 0.99)
update_label()
elif event.is_action_pressed("increase_fog_density"):
get_world_3d().environment.volumetric_fog_density = clamp(get_world_3d().environment.volumetric_fog_density + 0.01, 0.0, 1.0)
update_label()
elif event.is_action_pressed("decrease_fog_density"):
get_world_3d().environment.volumetric_fog_density = clamp(get_world_3d().environment.volumetric_fog_density - 0.01, 0.0, 1.0)
update_label()
elif event.is_action_pressed("increase_volumetric_fog_quality"):
volumetric_fog_volume_size = clamp(volumetric_fog_volume_size + 16, 16, 384)
volumetric_fog_volume_depth = clamp(volumetric_fog_volume_depth + 16, 16, 384)
RenderingServer.environment_set_volumetric_fog_volume_size(volumetric_fog_volume_size, volumetric_fog_volume_depth)
update_label()
elif event.is_action_pressed("decrease_volumetric_fog_quality"):
volumetric_fog_volume_size = clamp(volumetric_fog_volume_size - 16, 16, 384)
volumetric_fog_volume_depth = clamp(volumetric_fog_volume_depth - 16, 16, 384)
RenderingServer.environment_set_volumetric_fog_volume_size(volumetric_fog_volume_size, volumetric_fog_volume_depth)
update_label()
func update_label() -> void:
if get_world_3d().environment.volumetric_fog_temporal_reprojection_enabled:
label.text = "Fog density: %.2f\nTemporal reprojection: Enabled\nTemporal reprojection strength: %.2f\nVolumetric fog quality: %d×%d×%d" % [
get_world_3d().environment.volumetric_fog_density,
get_world_3d().environment.volumetric_fog_temporal_reprojection_amount,
volumetric_fog_volume_size,
volumetric_fog_volume_size,
volumetric_fog_volume_depth,
]
else:
label.text = "Fog density: %.2f\nTemporal reprojection: Disabled\nVolumetric fog quality: %d×%d×%d" % [
get_world_3d().environment.volumetric_fog_density,
volumetric_fog_volume_size,
volumetric_fog_volume_size,
volumetric_fog_volume_depth,
]
| |
117980
|
extends Camera3D
var collision_exception := []
var max_height := 2.0
var min_height := 0
@export var min_distance := 0.5
@export var max_distance := 3.0
@export var angle_v_adjust := 0.0
@onready var target_node: Node3D = get_parent()
func _ready() -> void:
collision_exception.append(target_node.get_parent().get_rid())
# Detach the camera transform from the parent spatial node.
top_level = true
func _physics_process(_delta: float) -> void:
var target_pos := target_node.global_transform.origin
var camera_pos := global_transform.origin
var delta_pos := camera_pos - target_pos
# Regular delta follow.
# Check ranges.
if delta_pos.length() < min_distance:
delta_pos = delta_pos.normalized() * min_distance
elif delta_pos.length() > max_distance:
delta_pos = delta_pos.normalized() * max_distance
# Check upper and lower height.
delta_pos.y = clamp(delta_pos.y, min_height, max_height)
camera_pos = target_pos + delta_pos
look_at_from_position(camera_pos, target_pos, Vector3.UP)
# Turn a little up or down.
var t := transform
t.basis = Basis(t.basis[0], deg_to_rad(angle_v_adjust)) * t.basis
transform = t
| |
118015
|
[gd_scene load_steps=11 format=3 uid="uid://csdy1t6j24awl"]
[ext_resource type="Texture2D" uid="uid://c2eorasvxyf5u" path="res://menu/main/title.png" id="1"]
[ext_resource type="Script" path="res://menu/main/splash_text.gd" id="2"]
[ext_resource type="Script" path="res://menu/main/main_menu.gd" id="3"]
[ext_resource type="Texture2D" uid="uid://c514noc8ngc4x" path="res://menu/main/dark_dirt.png" id="4"]
[ext_resource type="PackedScene" uid="uid://e22n700qhxqr" path="res://menu/options/options.tscn" id="5"]
[ext_resource type="Theme" uid="uid://ckax6htygmelo" path="res://menu/theme/theme.tres" id="6"]
[ext_resource type="Texture2D" uid="uid://ej6lqf2fptv8" path="res://menu/button.png" id="7"]
[ext_resource type="Texture2D" uid="uid://blcjvv0p0a6v8" path="res://menu/button_pressed.png" id="7_hsmm5"]
[ext_resource type="Texture2D" uid="uid://cfh73c8wnvgol" path="res://menu/button_hover.png" id="8_tutt7"]
[ext_resource type="Texture2D" uid="uid://h208mfx7dyy2" path="res://menu/button_focus.png" id="9_d3hm1"]
[node name="MainMenu" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme = ExtResource("6")
script = ExtResource("3")
[node name="Background" type="TextureRect" parent="."]
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
texture = ExtResource("4")
stretch_mode = 1
[node name="TitleScreen" type="VBoxContainer" parent="."]
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
[node name="Logo" type="CenterContainer" parent="TitleScreen"]
texture_repeat = 2
custom_minimum_size = Vector2(0, 350)
layout_mode = 2
[node name="Logo" type="TextureRect" parent="TitleScreen/Logo"]
layout_mode = 2
texture = ExtResource("1")
[node name="SplashHolder" type="Control" parent="TitleScreen/Logo/Logo"]
layout_mode = 1
anchors_preset = 3
anchor_left = 1.0
anchor_top = 1.0
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = -36.0
offset_right = -36.0
grow_horizontal = 0
grow_vertical = 0
script = ExtResource("2")
[node name="SplashText" type="Label" parent="TitleScreen/Logo/Logo/SplashHolder"]
modulate = Color(1, 1, 0, 1)
texture_filter = 1
layout_mode = 0
anchor_left = 1.0
anchor_top = 1.0
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = -120.0
offset_right = 124.0
offset_bottom = 52.0
grow_horizontal = 0
grow_vertical = 0
rotation = -0.261799
theme_override_font_sizes/font_size = 61
text = "Made in Godot!"
[node name="ButtonHolder" type="HBoxContainer" parent="TitleScreen"]
layout_mode = 2
size_flags_vertical = 2
alignment = 1
[node name="MainButtons" type="VBoxContainer" parent="TitleScreen/ButtonHolder"]
layout_mode = 2
theme_override_constants/separation = 20
alignment = 1
[node name="Start" type="TextureButton" parent="TitleScreen/ButtonHolder/MainButtons"]
layout_mode = 2
texture_normal = ExtResource("7")
texture_pressed = ExtResource("7_hsmm5")
texture_hover = ExtResource("8_tutt7")
texture_focused = ExtResource("9_d3hm1")
[node name="Label" type="Label" parent="TitleScreen/ButtonHolder/MainButtons/Start"]
texture_filter = 1
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
offset_top = -1.0
offset_bottom = -18.0
grow_horizontal = 2
grow_vertical = 2
theme_override_font_sizes/font_size = 60
text = "Start Game"
horizontal_alignment = 1
vertical_alignment = 1
[node name="Options" type="TextureButton" parent="TitleScreen/ButtonHolder/MainButtons"]
layout_mode = 2
texture_normal = ExtResource("7")
texture_pressed = ExtResource("7_hsmm5")
texture_hover = ExtResource("8_tutt7")
texture_focused = ExtResource("9_d3hm1")
[node name="Label" type="Label" parent="TitleScreen/ButtonHolder/MainButtons/Options"]
texture_filter = 1
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
offset_top = -1.0
offset_bottom = -18.0
grow_horizontal = 2
grow_vertical = 2
theme_override_font_sizes/font_size = 60
text = "Options"
horizontal_alignment = 1
vertical_alignment = 1
[node name="Exit" type="TextureButton" parent="TitleScreen/ButtonHolder/MainButtons"]
layout_mode = 2
texture_normal = ExtResource("7")
texture_pressed = ExtResource("7_hsmm5")
texture_hover = ExtResource("8_tutt7")
texture_focused = ExtResource("9_d3hm1")
[node name="Label" type="Label" parent="TitleScreen/ButtonHolder/MainButtons/Exit"]
texture_filter = 1
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
offset_top = -1.0
offset_bottom = -18.0
grow_horizontal = 2
grow_vertical = 2
theme_override_font_sizes/font_size = 60
text = "Exit Game"
horizontal_alignment = 1
vertical_alignment = 1
[node name="Spacer" type="Control" parent="TitleScreen"]
layout_mode = 2
[node name="StartGame" type="HBoxContainer" parent="."]
visible = false
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
alignment = 1
[node name="StartButtons" type="VBoxContainer" parent="StartGame"]
layout_mode = 2
theme_override_constants/separation = 20
alignment = 1
[node name="Spacer" type="Control" parent="StartGame/StartButtons"]
layout_mode = 2
[node name="RandomBlocks" type="TextureButton" parent="StartGame/StartButtons"]
layout_mode = 2
texture_normal = ExtResource("7")
texture_pressed = ExtResource("7_hsmm5")
texture_hover = ExtResource("8_tutt7")
texture_focused = ExtResource("9_d3hm1")
[node name="Label" type="Label" parent="StartGame/StartButtons/RandomBlocks"]
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
offset_top = -1.0
offset_bottom = -18.0
grow_horizontal = 2
grow_vertical = 2
theme_override_font_sizes/font_size = 60
text = "Random Blocks"
horizontal_alignment = 1
vertical_alignment = 1
[node name="FlatGrass" type="TextureButton" parent="StartGame/StartButtons"]
layout_mode = 2
texture_normal = ExtResource("7")
texture_pressed = ExtResource("7_hsmm5")
texture_hover = ExtResource("8_tutt7")
texture_focused = ExtResource("9_d3hm1")
[node name="Label" type="Label" parent="StartGame/StartButtons/FlatGrass"]
layout_mode = 0
anchor_right = 1.0
anchor_bottom = 1.0
offset_top = -1.0
offset_bottom = -18.0
grow_horizontal = 2
grow_vertical = 2
theme_override_font_sizes/font_size = 60
text = "Flat Grass"
horizontal_alignment = 1
vertical_alignment = 1
[node name="BackToTitle" type="TextureButton" parent="StartGame/StartButtons"]
layout_mode = 2
texture_normal = ExtResource("7")
texture_pressed = ExtResource("7_hsmm5")
texture_hover = ExtResource("8_tutt7")
texture_focused = ExtResource("9_d3hm1")
| |
118019
|
extends CharacterBody3D
const EYE_HEIGHT_STAND = 1.6
const EYE_HEIGHT_CROUCH = 1.4
const MOVEMENT_SPEED_GROUND = 0.6
const MOVEMENT_SPEED_AIR = 0.11
const MOVEMENT_SPEED_CROUCH_MODIFIER = 0.5
const MOVEMENT_FRICTION_GROUND = 0.9
const MOVEMENT_FRICTION_AIR = 0.98
var _mouse_motion := Vector2()
var _selected_block := 6
@onready var gravity := float(ProjectSettings.get_setting("physics/3d/default_gravity"))
@onready var head: Node3D = $Head
@onready var raycast: RayCast3D = $Head/RayCast3D
@onready var camera_attributes: CameraAttributes = $Head/Camera3D.attributes
@onready var selected_block_texture: TextureRect = $SelectedBlock
@onready var voxel_world: Node = $"../VoxelWorld"
@onready var crosshair: CenterContainer = $"../PauseMenu/Crosshair"
func _ready() -> void:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _process(_delta: float) -> void:
# Mouse movement.
_mouse_motion.y = clampf(_mouse_motion.y, -1560, 1560)
transform.basis = Basis.from_euler(Vector3(0, _mouse_motion.x * -0.001, 0))
head.transform.basis = Basis.from_euler(Vector3(_mouse_motion.y * -0.001, 0, 0))
# Block selection.
var ray_position := raycast.get_collision_point()
var ray_normal := raycast.get_collision_normal()
if Input.is_action_just_pressed(&"pick_block"):
# Block picking.
var block_global_position := Vector3i((ray_position - ray_normal / 2).floor())
_selected_block = voxel_world.get_block_global_position(block_global_position)
else:
# Block prev/next keys.
if Input.is_action_just_pressed(&"prev_block"):
_selected_block -= 1
if Input.is_action_just_pressed(&"next_block"):
_selected_block += 1
_selected_block = wrapi(_selected_block, 1, 30)
# Set the appropriate texture.
var uv := Chunk.calculate_block_uvs(_selected_block)
selected_block_texture.texture.region = Rect2(uv[0] * 512, Vector2.ONE * 64)
# Block breaking/placing.
if crosshair.visible and raycast.is_colliding():
var breaking := Input.is_action_just_pressed(&"break")
var placing := Input.is_action_just_pressed(&"place")
# Either both buttons were pressed or neither are, so stop.
if breaking == placing:
return
if breaking:
var block_global_position := Vector3i((ray_position - ray_normal / 2).floor())
voxel_world.set_block_global_position(block_global_position, 0)
elif placing:
var block_global_position := Vector3i((ray_position + ray_normal / 2).floor())
voxel_world.set_block_global_position(block_global_position, _selected_block)
func _physics_process(delta: float) -> void:
camera_attributes.dof_blur_far_enabled = Settings.fog_enabled
camera_attributes.dof_blur_far_distance = Settings.fog_distance * 1.5
camera_attributes.dof_blur_far_transition = Settings.fog_distance * 0.125
# Crouching.
var crouching := Input.is_action_pressed(&"crouch")
head.transform.origin.y = lerpf(head.transform.origin.y, EYE_HEIGHT_CROUCH if crouching else EYE_HEIGHT_STAND, 16 * delta)
# Keyboard movement.
var movement_vec2 := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
var movement := transform.basis * (Vector3(movement_vec2.x, 0, movement_vec2.y))
if is_on_floor():
movement *= MOVEMENT_SPEED_GROUND
else:
movement *= MOVEMENT_SPEED_AIR
if crouching:
movement *= MOVEMENT_SPEED_CROUCH_MODIFIER
# Gravity.
velocity.y -= gravity * delta
velocity += Vector3(movement.x, 0, movement.z)
# Apply horizontal friction.
velocity.x *= MOVEMENT_FRICTION_GROUND if is_on_floor() else MOVEMENT_FRICTION_AIR
velocity.z *= MOVEMENT_FRICTION_GROUND if is_on_floor() else MOVEMENT_FRICTION_AIR
move_and_slide()
# Jumping, applied next frame.
if is_on_floor() and Input.is_action_pressed(&"jump"):
velocity.y = 7.5
func _input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
_mouse_motion += event.relative
func chunk_pos() -> Vector3i:
return Vector3i((transform.origin / Chunk.CHUNK_SIZE).floor())
| |
118029
|
[node name="TestName" type="Label" parent="."]
anchors_preset = 7
anchor_left = 0.5
anchor_top = 1.0
anchor_right = 0.5
anchor_bottom = 1.0
offset_left = -192.0
offset_top = -58.0
offset_right = 192.0
offset_bottom = -24.0
grow_horizontal = 2
grow_vertical = 0
theme_override_colors/font_outline_color = Color(0, 0, 0, 1)
theme_override_constants/outline_size = 5
theme_override_font_sizes/font_size = 24
horizontal_alignment = 1
[node name="Previous" type="Button" parent="."]
anchors_preset = 2
anchor_top = 1.0
anchor_bottom = 1.0
offset_left = 24.0
offset_top = -55.0
offset_right = 135.0
offset_bottom = -24.0
grow_vertical = 0
text = "« Previous"
[node name="Next" type="Button" parent="."]
anchors_preset = 3
anchor_left = 1.0
anchor_top = 1.0
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = -107.0
offset_top = -55.0
offset_right = -24.0
offset_bottom = -24.0
grow_horizontal = 0
grow_vertical = 0
text = "Next »"
[connection signal="pressed" from="Previous" to="." method="_on_previous_pressed"]
[connection signal="pressed" from="Next" to="." method="_on_next_pressed"]
| |
118035
|
extends WorldEnvironment
const ROT_SPEED = 0.003
const ZOOM_SPEED = 0.125
const MAIN_BUTTONS = MOUSE_BUTTON_MASK_LEFT | MOUSE_BUTTON_MASK_RIGHT | MOUSE_BUTTON_MASK_MIDDLE
var tester_index := 0
var rot_x := deg_to_rad(-22.5) # This must be kept in sync with RotationX.
var rot_y := deg_to_rad(90) # This must be kept in sync with CameraHolder.
var zoom := 2.5
var base_height := int(ProjectSettings.get_setting("display/window/size/viewport_height"))
@onready var testers: Node3D = $Testers
@onready var camera_holder: Node3D = $CameraHolder # Has a position and rotates on Y.
@onready var rotation_x: Node3D = $CameraHolder/RotationX
@onready var camera: Camera3D = $CameraHolder/RotationX/Camera3D
func _ready() -> void:
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
update_gui()
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed(&"ui_left"):
_on_previous_pressed()
if event.is_action_pressed(&"ui_right"):
_on_next_pressed()
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
zoom -= ZOOM_SPEED
if event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
zoom += ZOOM_SPEED
zoom = clamp(zoom, 1.5, 4)
if event is InputEventMouseMotion and event.button_mask & MAIN_BUTTONS:
# Compensate motion speed to be resolution-independent (based on the window height).
var relative_motion: Vector2 = event.relative * DisplayServer.window_get_size().y / base_height
rot_y -= relative_motion.x * ROT_SPEED
rot_x -= relative_motion.y * ROT_SPEED
rot_x = clamp(rot_x, deg_to_rad(-90), 0)
camera_holder.transform.basis = Basis.from_euler(Vector3(0, rot_y, 0))
rotation_x.transform.basis = Basis.from_euler(Vector3(rot_x, 0, 0))
func _process(delta: float) -> void:
var current_tester: Node3D = testers.get_child(tester_index)
# This code assumes CameraHolder's X and Y coordinates are already correct.
var current_position := camera_holder.global_transform.origin.z
var target_position := current_tester.global_transform.origin.z
camera_holder.global_transform.origin.z = lerpf(current_position, target_position, 3 * delta)
camera.position.z = lerpf(camera.position.z, zoom, 10 * delta)
func _on_previous_pressed() -> void:
tester_index = max(0, tester_index - 1)
update_gui()
func _on_next_pressed() -> void:
tester_index = min(tester_index + 1, testers.get_child_count() - 1)
update_gui()
func update_gui() -> void:
$TestName.text = str(testers.get_child(tester_index).name).capitalize()
$Previous.disabled = tester_index == 0
$Next.disabled = tester_index == testers.get_child_count() - 1
| |
118072
|
extends Camera3D
# Higher values cause the field of view to increase more at high speeds.
const FOV_SPEED_FACTOR = 60
# Higher values cause the field of view to adapt to speed changes faster.
const FOV_SMOOTH_FACTOR = 0.2
# Don't change FOV if moving below this speed. This prevents shadows from flickering when driving slowly.
const FOV_CHANGE_MIN_SPEED = 0.05
@export var min_distance := 2.0
@export var max_distance := 4.0
@export var angle_v_adjust := 0.0
@export var height := 1.5
var camera_type := CameraType.EXTERIOR
var initial_transform := transform
var base_fov := fov
# The field of view to smoothly interpolate to.
var desired_fov := fov
# Position on the last physics frame (used to measure speed).
@onready var previous_position := global_position
enum CameraType {
EXTERIOR,
INTERIOR,
TOP_DOWN,
MAX, # Represents the size of the CameraType enum.
}
func _ready() -> void:
update_camera()
func _input(event: InputEvent) -> void:
if event.is_action_pressed(&"cycle_camera"):
camera_type = wrapi(camera_type + 1, 0, CameraType.MAX) as CameraType
update_camera()
func _physics_process(_delta: float) -> void:
if camera_type == CameraType.EXTERIOR:
var target: Vector3 = get_parent().global_transform.origin
var pos := global_transform.origin
var from_target := pos - target
# Check ranges.
if from_target.length() < min_distance:
from_target = from_target.normalized() * min_distance
elif from_target.length() > max_distance:
from_target = from_target.normalized() * max_distance
from_target.y = height
pos = target + from_target
look_at_from_position(pos, target, Vector3.UP)
elif camera_type == CameraType.TOP_DOWN:
position.x = get_parent().global_transform.origin.x
position.z = get_parent().global_transform.origin.z
# Force rotation to prevent camera from being slanted after switching cameras while on a slope.
rotation_degrees = Vector3(270, 180, 0)
# Dynamic field of view based on car speed, with smoothing to prevent sudden changes on impact.
desired_fov = clamp(base_fov + (abs(global_position.length() - previous_position.length()) - FOV_CHANGE_MIN_SPEED) * FOV_SPEED_FACTOR, base_fov, 100)
fov = lerpf(fov, desired_fov, FOV_SMOOTH_FACTOR)
# Turn a little up or down
transform.basis = Basis(transform.basis[0], deg_to_rad(angle_v_adjust)) * transform.basis
previous_position = global_position
func update_camera() -> void:
match camera_type:
CameraType.EXTERIOR:
transform = initial_transform
CameraType.INTERIOR:
global_transform = get_node(^"../../InteriorCameraPosition").global_transform
CameraType.TOP_DOWN:
global_transform = get_node(^"../../TopDownCameraPosition").global_transform
# This detaches the camera transform from the parent spatial node, but only
# for exterior and top-down cameras.
set_as_top_level(camera_type != CameraType.INTERIOR)
| |
118110
|
[gd_scene load_steps=15 format=3 uid="uid://2y3ar4s86yra"]
[ext_resource type="Script" path="res://Main.gd" id="1"]
[ext_resource type="PackedScene" uid="uid://dp478jyugrn7o" path="res://Player.tscn" id="2"]
[ext_resource type="PackedScene" uid="uid://ha0ar5s2c3m4" path="res://Mob.tscn" id="3"]
[ext_resource type="Theme" uid="uid://cqquurjk1i7yw" path="res://ui_theme.tres" id="4_gnyca"]
[ext_resource type="Script" path="res://ScoreLabel.gd" id="6"]
[sub_resource type="BoxShape3D" id="1"]
size = Vector3(60, 2, 60)
[sub_resource type="BoxMesh" id="2"]
size = Vector3(60, 2, 60)
[sub_resource type="WorldBoundaryShape3D" id="WorldBoundaryShape3D_i5n5q"]
[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_m3njk"]
sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
[sub_resource type="Sky" id="Sky_yutuu"]
sky_material = SubResource("ProceduralSkyMaterial_m3njk")
[sub_resource type="Environment" id="Environment_0tcge"]
background_mode = 2
sky = SubResource("Sky_yutuu")
tonemap_mode = 2
[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_cr5ed"]
albedo_color = Color(0.635294, 0.211765, 0.0235294, 1)
[sub_resource type="CylinderMesh" id="3"]
material = SubResource("StandardMaterial3D_cr5ed")
radial_segments = 24
rings = 1
[sub_resource type="Curve3D" id="5"]
_data = {
"points": PackedVector3Array(0, 0, 0, 0, 0, 0, 14, 0, -15, 0, 0, 0, 0, 0, 0, -13, 0, -15, 0, 0, 0, 0, 0, 0, -13, 0, 16, 0, 0, 0, 0, 0, 0, 14, 0, 16, 0, 0, 0, 0, 0, 0, 14, 0, -15),
"tilts": PackedFloat32Array(0, 0, 0, 0, 0)
}
point_count = 5
[node name="Main" type="Node"]
script = ExtResource("1")
mob_scene = ExtResource("3")
[node name="Ground" type="StaticBody3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0)
collision_layer = 4
collision_mask = 0
[node name="CollisionShape" type="CollisionShape3D" parent="Ground"]
shape = SubResource("1")
[node name="MeshInstance" type="MeshInstance3D" parent="Ground"]
mesh = SubResource("2")
[node name="Walls" type="StaticBody3D" parent="."]
editor_description = "These invisible walls are used to prevent the player from escaping the playable area.
These walls use WorldBoundaryShape3D collision shapes, which are infinitely large planes
(even though they look finite in the editor)."
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 5)
collision_layer = 4
collision_mask = 0
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls"]
transform = Transform3D(1, 0, 0, 0, 1.31134e-07, 1, 0, -1, 1.31134e-07, 0, 10, 11)
shape = SubResource("WorldBoundaryShape3D_i5n5q")
[node name="CollisionShape3D2" type="CollisionShape3D" parent="Walls"]
transform = Transform3D(-4.37114e-08, 1, -1.31134e-07, 0, 1.31134e-07, 1, 1, 4.37114e-08, -5.73206e-15, -13, 10, -4.76837e-07)
shape = SubResource("WorldBoundaryShape3D_i5n5q")
[node name="CollisionShape3D3" type="CollisionShape3D" parent="Walls"]
transform = Transform3D(4.37114e-08, -1, 2.18557e-07, 3.82137e-15, -2.18557e-07, -1, 1, 4.37114e-08, -5.73206e-15, 14, 10, -4.76837e-07)
shape = SubResource("WorldBoundaryShape3D_i5n5q")
[node name="CollisionShape3D4" type="CollisionShape3D" parent="Walls"]
transform = Transform3D(1, 5.96046e-08, -1.42109e-14, 3.82137e-15, -2.18557e-07, -1, -5.96046e-08, 1, -2.18557e-07, 9.53674e-07, 10, -20)
shape = SubResource("WorldBoundaryShape3D_i5n5q")
[node name="DirectionalLight" type="DirectionalLight3D" parent="."]
transform = Transform3D(0.5, -0.777049, 0.382355, 0, 0.441506, 0.897258, -0.866025, -0.448629, 0.220753, 0, 12.5592, 14.7757)
shadow_enabled = true
shadow_bias = 0.04
shadow_blur = 1.5
directional_shadow_mode = 0
directional_shadow_fade_start = 1.0
directional_shadow_max_distance = 40.0
[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
environment = SubResource("Environment_0tcge")
[node name="Player" parent="." instance=ExtResource("2")]
[node name="CameraPivot" type="Marker3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 0.707107, 0.707107, 0, -0.707107, 0.707107, 0.183514, 0, 0)
[node name="Camera" type="Camera3D" parent="CameraPivot"]
transform = Transform3D(1, 0, 0, 0, 1, -2.98023e-08, 0, 2.98023e-08, 1, 0, 9.53674e-07, 19)
projection = 1
fov = 48.6
size = 24.0
far = 40.0
[node name="Cylinders" type="Node3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0)
[node name="MeshInstance" type="MeshInstance3D" parent="Cylinders"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6, 1, -15)
mesh = SubResource("3")
[node name="MeshInstance3" type="MeshInstance3D" parent="Cylinders"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -21, 1, -15)
mesh = SubResource("3")
[node name="MeshInstance2" type="MeshInstance3D" parent="Cylinders"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -21, 1, 16)
mesh = SubResource("3")
| |
118112
|
[gd_scene load_steps=8 format=3 uid="uid://dp478jyugrn7o"]
[ext_resource type="Script" path="res://Player.gd" id="1"]
[ext_resource type="PackedScene" uid="uid://d0ypm0v45pwdv" path="res://art/player.glb" id="2"]
[sub_resource type="SphereShape3D" id="1"]
radius = 0.792278
[sub_resource type="CylinderShape3D" id="2"]
height = 0.1438
radius = 0.907607
[sub_resource type="CylinderShape3D" id="CylinderShape3D_76fa1"]
height = 0.144
radius = 0.2
[sub_resource type="Animation" id="3"]
length = 1.2
loop_mode = 1
tracks/0/type = "value"
tracks/0/imported = false
tracks/0/enabled = true
tracks/0/path = NodePath("Pivot/Character:position")
tracks/0/interp = 1
tracks/0/loop_wrap = true
tracks/0/keys = {
"times": PackedFloat32Array(0.22, 0.7, 1.18),
"transitions": PackedFloat32Array(0.435275, 2.21914, 1),
"update": 0,
"values": [Vector3(0, 0.329753, 0), Vector3(0, 0.660351, 0), Vector3(0, 0.349734, 0)]
}
tracks/1/type = "value"
tracks/1/imported = false
tracks/1/enabled = true
tracks/1/path = NodePath("Pivot/Character:rotation_degrees")
tracks/1/interp = 1
tracks/1/loop_wrap = true
tracks/1/keys = {
"times": PackedFloat32Array(0.1, 0.46, 1.18),
"transitions": PackedFloat32Array(0.482968, 0.535887, 1),
"update": 0,
"values": [Vector3(-5.0326, 0, 0), Vector3(10, 0, 0), Vector3(-10, 0, 0)]
}
[sub_resource type="AnimationLibrary" id="AnimationLibrary_aq6tr"]
_data = {
"float": SubResource("3")
}
[node name="Player" type="CharacterBody3D"]
collision_mask = 2147483654
script = ExtResource("1")
[node name="Pivot" type="Node3D" parent="."]
[node name="Character" parent="Pivot" instance=ExtResource("2")]
transform = Transform3D(1, 0, 0, 0, 0.984808, 0.173648, 0, -0.173648, 0.984808, 0, 0.349734, 0)
[node name="CollisionShape" type="CollisionShape3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.771765, 0)
shape = SubResource("1")
[node name="MobDetector" type="Area3D" parent="."]
collision_layer = 0
collision_mask = 2
monitorable = false
[node name="CollisionShape" type="CollisionShape3D" parent="MobDetector"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.06491, 0)
shape = SubResource("2")
[node name="CollisionShape2" type="CollisionShape3D" parent="MobDetector"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.455268, 0.95, 1.1423)
shape = SubResource("CylinderShape3D_76fa1")
[node name="CollisionShape3" type="CollisionShape3D" parent="MobDetector"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.716365, 0.95, 1.71889)
shape = SubResource("CylinderShape3D_76fa1")
[node name="CollisionShape4" type="CollisionShape3D" parent="MobDetector"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.730546, 0.95, 1.69713)
shape = SubResource("CylinderShape3D_76fa1")
[node name="CollisionShape5" type="CollisionShape3D" parent="MobDetector"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.45857, 0.95, 1.15318)
shape = SubResource("CylinderShape3D_76fa1")
[node name="AnimationPlayer" type="AnimationPlayer" parent="."]
libraries = {
"": SubResource("AnimationLibrary_aq6tr")
}
autoplay = "float"
[connection signal="body_entered" from="MobDetector" to="." method="_on_MobDetector_body_entered"]
| |
118115
|
extends CharacterBody3D
signal hit
## How fast the player moves in meters per second.
@export var speed = 14
## Vertical impulse applied to the character upon jumping in meters per second.
@export var jump_impulse = 20
## Vertical impulse applied to the character upon bouncing over a mob in meters per second.
@export var bounce_impulse = 16
## The downward acceleration when in the air, in meters per second.
@export var fall_acceleration = 75
func _physics_process(delta):
var direction = Vector3.ZERO
if Input.is_action_pressed("move_right"):
direction.x += 1
if Input.is_action_pressed("move_left"):
direction.x -= 1
if Input.is_action_pressed("move_back"):
direction.z += 1
if Input.is_action_pressed("move_forward"):
direction.z -= 1
if direction != Vector3.ZERO:
# In the lines below, we turn the character when moving and make the animation play faster.
direction = direction.normalized()
# Setting the basis property will affect the rotation of the node.
basis = Basis.looking_at(direction)
$AnimationPlayer.speed_scale = 4
else:
$AnimationPlayer.speed_scale = 1
velocity.x = direction.x * speed
velocity.z = direction.z * speed
# Jumping.
if is_on_floor() and Input.is_action_just_pressed("jump"):
velocity.y += jump_impulse
# We apply gravity every frame so the character always collides with the ground when moving.
# This is necessary for the is_on_floor() function to work as a body can always detect
# the floor, walls, etc. when a collision happens the same frame.
velocity.y -= fall_acceleration * delta
move_and_slide()
# Here, we check if we landed on top of a mob and if so, we kill it and bounce.
# With move_and_slide(), Godot makes the body move sometimes multiple times in a row to
# smooth out the character's motion. So we have to loop over all collisions that may have
# happened.
# If there are no "slides" this frame, the loop below won't run.
for index in range(get_slide_collision_count()):
var collision = get_slide_collision(index)
if collision.get_collider().is_in_group("mob"):
var mob = collision.get_collider()
if Vector3.UP.dot(collision.get_normal()) > 0.1:
mob.squash()
velocity.y = bounce_impulse
# Prevent this block from running more than once,
# which would award the player more than 1 point for squashing a single mob.
break
# This makes the character follow a nice arc when jumping
rotation.x = PI / 6 * velocity.y / jump_impulse
func die():
hit.emit()
queue_free()
func _on_MobDetector_body_entered(_body):
die()
| |
118117
|
extends CharacterBody3D
# Emitted when the player jumped on the mob.
signal squashed
## Minimum speed of the mob in meters per second.
@export var min_speed = 10
## Maximum speed of the mob in meters per second.
@export var max_speed = 18
func _physics_process(_delta):
move_and_slide()
func initialize(start_position, player_position):
look_at_from_position(start_position, player_position, Vector3.UP)
rotate_y(randf_range(-PI / 4, PI / 4))
var random_speed = randf_range(min_speed, max_speed)
# We calculate a forward velocity first, which represents the speed.
velocity = Vector3.FORWARD * random_speed
# We then rotate the vector based on the mob's Y rotation to move in the direction it's looking.
velocity = velocity.rotated(Vector3.UP, rotation.y)
$AnimationPlayer.speed_scale = random_speed / min_speed
func squash():
squashed.emit()
queue_free()
func _on_visible_on_screen_notifier_screen_exited():
queue_free()
| |
118135
|
extends Camera3D
const MOUSE_SENSITIVITY = 0.002
const MOVE_SPEED = 1.5
var rot := Vector3()
var velocity := Vector3()
func _ready() -> void:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _input(event: InputEvent) -> void:
# Mouse look (only if the mouse is captured).
if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
# Horizontal mouse look.
rot.y -= event.relative.x * MOUSE_SENSITIVITY
# Vertical mouse look.
rot.x = clamp(rot.x - event.relative.y * MOUSE_SENSITIVITY, -1.57, 1.57)
transform.basis = Basis.from_euler(rot)
if event.is_action_pressed("toggle_mouse_capture"):
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
else:
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _process(delta: float) -> void:
var motion := Vector3(
Input.get_axis(&"move_left", &"move_right"),
0,
Input.get_axis(&"move_forward", &"move_back")
)
# Normalize motion to prevent diagonal movement from being
# `sqrt(2)` times faster than straight movement.
motion = motion.normalized()
velocity += MOVE_SPEED * delta * (transform.basis * motion)
velocity *= 0.85
position += velocity
| |
118217
|
extends CharacterBody3D
const MAX_SPEED = 3.5
const JUMP_SPEED = 6.5
const ACCELERATION = 4
const DECELERATION = 4
@onready var camera: Camera3D = $Target/Camera3D
@onready var gravity := float(-ProjectSettings.get_setting("physics/3d/default_gravity"))
@onready var start_position := position
func _physics_process(delta: float) -> void:
if Input.is_action_just_pressed(&"exit"):
get_tree().quit()
if Input.is_action_just_pressed(&"reset_position") or global_position.y < - 6:
# Pressed the reset key or fell off the ground.
position = start_position
velocity = Vector3.ZERO
var dir := Vector3()
dir.x = Input.get_axis(&"move_left", &"move_right")
dir.z = Input.get_axis(&"move_forward", &"move_back")
# Get the camera's transform basis, but remove the X rotation such
# that the Y axis is up and Z is horizontal.
var cam_basis := camera.global_transform.basis
cam_basis = cam_basis.rotated(cam_basis.x, -cam_basis.get_euler().x)
dir = cam_basis * dir
# Limit the input to a length of 1. `length_squared()` is faster to check
# than `length()`.
if dir.length_squared() > 1:
dir /= dir.length()
# Apply gravity.
velocity.y += delta * gravity
# Using only the horizontal velocity, interpolate towards the input.
var hvel := velocity
hvel.y = 0
var target := dir * MAX_SPEED
var acceleration := 0.0
if dir.dot(hvel) > 0:
acceleration = ACCELERATION
else:
acceleration = DECELERATION
hvel = hvel.lerp(target, acceleration * delta)
# Assign hvel's values back to velocity, and then move.
velocity.x = hvel.x
velocity.z = hvel.z
# TODO: This information should be set to the CharacterBody properties instead of arguments: , Vector3.UP
# TODO: Rename velocity to linear_velocity in the rest of the script.
move_and_slide()
# TODO: This information should be set to the CharacterBody properties instead of arguments.
# Jumping code. is_on_floor() must come after move_and_slide().
if is_on_floor() and Input.is_action_pressed(&"jump"):
velocity.y = JUMP_SPEED
func _on_tcube_body_entered(body: PhysicsBody3D) -> void:
if body == self:
$WinText.show()
| |
118218
|
extends Camera3D
@export var min_distance := 0.5
@export var max_distance := 3.0
@export var angle_v_adjust := 0.0
var collision_exception := []
var max_height := 2.0
var min_height := 0
@onready var target_node: Node3D = get_parent()
func _ready() -> void:
collision_exception.append(target_node.get_parent().get_rid())
# Detaches the camera transform from the parent spatial node.
top_level = true
func _physics_process(_delta: float) -> void:
var target_pos := target_node.global_transform.origin
var camera_pos := global_transform.origin
var delta_pos := camera_pos - target_pos
# Regular delta follow.
# Check ranges.
if delta_pos.length() < min_distance:
delta_pos = delta_pos.normalized() * min_distance
elif delta_pos.length() > max_distance:
delta_pos = delta_pos.normalized() * max_distance
# Check upper and lower height.
if delta_pos.y > max_height:
delta_pos.y = max_height
if delta_pos.y < min_height:
delta_pos.y = min_height
camera_pos = target_pos + delta_pos
look_at_from_position(camera_pos, target_pos, Vector3.UP)
# Turn a little up or down.
var t := transform
t.basis = Basis(t.basis[0], deg_to_rad(angle_v_adjust)) * t.basis
transform = t
| |
118253
|
extends Button
@export_file var scene_to_change_to: String = ""
func _ready():
pressed.connect(change_scene)
func change_scene():
if not scene_to_change_to.is_empty():
get_tree().change_scene_to_file(scene_to_change_to)
| |
118264
|
@tool
extends Node3D
# A FABRIK IK chain with a middle joint helper.
# The delta/tolerance for the bone chain (how do the bones need to be before it is considered satisfactory)
const CHAIN_TOLERANCE = 0.01
# The amount of interations the bone chain will go through in an attempt to get to the target position
const CHAIN_MAX_ITER = 10
@export var skeleton_path: NodePath:
set(value):
skeleton_path = value
# Because get_node doesn't work in the first call, we just want to assign instead
if first_call:
return
if skeleton_path == null:
if debug_messages:
printerr(name, " - IK_FABRIK: No Nodepath selected for skeleton_path!")
return
var temp = get_node(skeleton_path)
if temp != null:
# If it has the method "get_bone_global_pose" it is likely a Skeleton3D
if temp.has_method("get_bone_global_pose"):
skeleton = temp
bone_IDs = {}
# (Delete all of the old bone nodes and) Make all of the bone nodes for each bone in the IK chain
_make_bone_nodes()
if debug_messages:
printerr(name, " - IK_FABRIK: Attached to a new skeleton")
# If not, then it's (likely) not a Skeleton3D node
else:
skeleton = null
if debug_messages:
printerr(name, " - IK_FABRIK: skeleton_path does not point to a skeleton!")
else:
if debug_messages:
printerr(name, " - IK_FABRIK: No Nodepath selected for skeleton_path!")
@export var bones_in_chain: PackedStringArray:
set(value):
bones_in_chain = value
_make_bone_nodes()
@export var bones_in_chain_lengths: PackedFloat32Array:
set(value):
bones_in_chain_lengths = value
total_length = INF
@export_enum("_process", "_physics_process", "_notification", "none") var update_mode: int = 0:
set(value):
update_mode = value
set_process(false)
set_physics_process(false)
set_notify_transform(false)
if update_mode == 0:
set_process(true)
elif update_mode == 1:
set_process(true)
elif update_mode == 2:
set_notify_transform(true)
else:
if debug_messages:
printerr(name, " - IK_FABRIK: Unknown update mode. NOT updating skeleton")
return
var target: Node3D = null
var skeleton: Skeleton3D
# A dictionary holding all of the bone IDs (from the skeleton) and a dictionary holding
# all of the bone helper nodes
var bone_IDs = {}
var bone_nodes = {}
# The position of the origin
var chain_origin = Vector3()
# The combined length of every bone in the bone chain
var total_length = INF
# The amount of iterations we've been through, and whether or not we want to limit our solver to CHAIN_MAX_ITER
# amounts of interations.
@export var chain_iterations: int = 0
@export var limit_chain_iterations: bool = true
# Should we reset chain_iterations on movement during our update method?
@export var reset_iterations_on_update: bool = false
# A boolean to track whether or not we want to move the middle joint towards middle joint target.
@export var use_middle_joint_target: bool = false
var middle_joint_target: Node3D = null
# Have we called _set_skeleton_path or not already. Due to some issues using exported NodePaths,
# we need to ignore the first _set_skeleton_path call.
var first_call = true
# A boolean to track whether or not we want to print debug messages
var debug_messages = false
func _ready():
if target == null:
# NOTE: You MUST have a node called Target as a child of this node!
# So we create one if one doesn't already exist.
if not has_node("Target"):
target = Node3D.new()
add_child(target)
if Engine.is_editor_hint():
if get_tree() != null:
if get_tree().edited_scene_root != null:
target.set_owner(get_tree().edited_scene_root)
target.name = &"Target"
else:
target = $Target
# If we are in the editor, we want to make a sphere at this node
if Engine.is_editor_hint():
_make_editor_sphere_at_node(target, Color.MAGENTA)
if middle_joint_target == null:
if not has_node("MiddleJoint"):
middle_joint_target = Node3D.new()
add_child(middle_joint_target)
if Engine.is_editor_hint():
if get_tree() != null:
if get_tree().edited_scene_root != null:
middle_joint_target.set_owner(get_tree().edited_scene_root)
middle_joint_target.name = &"MiddleJoint"
else:
middle_joint_target = get_node(^"MiddleJoint")
# If we are in the editor, we want to make a sphere at this node
if Engine.is_editor_hint():
_make_editor_sphere_at_node(middle_joint_target, Color(1, 0.24, 1, 1))
# Make all of the bone nodes for each bone in the IK chain
_make_bone_nodes()
# Make sure we're using the right update mode
update_mode = update_mode
# Various upate methods
func _process(_delta):
if reset_iterations_on_update:
chain_iterations = 0
update_skeleton()
func _physics_process(_delta):
if reset_iterations_on_update:
chain_iterations = 0
update_skeleton()
func _notification(what):
if what == NOTIFICATION_TRANSFORM_CHANGED:
if reset_iterations_on_update:
chain_iterations = 0
update_skeleton()
############# IK SOLVER RELATED FUNCTIONS #############
func update_skeleton():
#### ERROR CHECKING conditions
if first_call:
skeleton_path = skeleton_path
first_call = false
if skeleton == null:
skeleton_path = skeleton_path
return
if bones_in_chain == null:
if debug_messages:
printerr(name, " - IK_FABRIK: No Bones in IK chain defined!")
return
if bones_in_chain_lengths == null:
if debug_messages:
printerr(name, " - IK_FABRIK: No Bone3D lengths in IK chain defined!")
return
if bones_in_chain.size() != bones_in_chain_lengths.size():
if debug_messages:
printerr(name, " - IK_FABRIK: bones_in_chain and bones_in_chain_lengths!")
return
################################
# Set all of the bone IDs in bone_IDs, if they are not already made
var i = 0
if bone_IDs.size() <= 0:
for bone_name in bones_in_chain:
bone_IDs[bone_name] = skeleton.find_bone(bone_name)
# Set the bone node to the currect bone position
bone_nodes[i].global_transform = get_bone_transform(i)
# If this is not the last bone in the bone chain, make it look at the next bone in the bone chain
if i < bone_IDs.size()-1:
bone_nodes[i].look_at(get_bone_transform(i+1).origin + skeleton.global_transform.origin, Vector3.UP)
i += 1
# Set the total length of the bone chain, if it is not already set
if total_length == INF:
total_length = 0
for bone_length in bones_in_chain_lengths:
total_length += bone_length
# Solve the bone chain
solve_chain()
| |
118267
|
@tool
extends Node3D
@export var skeleton_path: NodePath:
set(value):
# Assign skeleton_path to whatever value is passed.
skeleton_path = value
# Because get_node doesn't work in the first call, we just want to assign instead.
# This is to get around a issue with NodePaths exposed to the editor.
if first_call:
return
_setup_skeleton_path()
@export var bone_name: String = ""
@export_enum("_process", "_physics_process", "_notification", "none") var update_mode: int = 0:
set(value):
update_mode = value
# Set all of our processes to false.
set_process(false)
set_physics_process(false)
set_notify_transform(false)
# Based on the value of passed to update, enable the correct process.
if update_mode == 0:
set_process(true)
if debug_messages:
print(name, " - IK_LookAt: updating skeleton using _process...")
elif update_mode == 1:
set_physics_process(true)
if debug_messages:
print(name, " - IK_LookAt: updating skeleton using _physics_process...")
elif update_mode == 2:
set_notify_transform(true)
if debug_messages:
print(name, " - IK_LookAt: updating skeleton using _notification...")
else:
if debug_messages:
print(name, " - IK_LookAt: NOT updating skeleton due to unknown update method...")
@export_enum("X-up", "Y-up", "Z-up") var look_at_axis: int = 1
@export_range(0.0, 1.0, 0.001) var interpolation: float = 1.0
@export var use_our_rotation_x: bool = false
@export var use_our_rotation_y: bool = false
@export var use_our_rotation_z: bool = false
@export var use_negative_our_rot: bool = false
@export var additional_rotation: Vector3 = Vector3()
@export var position_using_additional_bone: bool = false
@export var additional_bone_name: String = ""
@export var additional_bone_length: float = 1
@export var debug_messages: bool = false
var skeleton_to_use: Skeleton3D = null
var first_call: bool = true
var _editor_indicator: Node3D = null
func _ready():
set_process(false)
set_physics_process(false)
set_notify_transform(false)
if update_mode == 0:
set_process(true)
elif update_mode == 1:
set_physics_process(true)
elif update_mode == 2:
set_notify_transform(true)
else:
if debug_messages:
print(name, " - IK_LookAt: Unknown update mode. NOT updating skeleton")
if Engine.is_editor_hint():
_setup_for_editor()
func _process(_delta):
update_skeleton()
func _physics_process(_delta):
update_skeleton()
func _notification(what):
if what == NOTIFICATION_TRANSFORM_CHANGED:
update_skeleton()
func update_skeleton():
# NOTE: Because get_node doesn't work in _ready, we need to skip
# a call before doing anything.
if first_call:
first_call = false
if skeleton_to_use == null:
_setup_skeleton_path()
# If we do not have a skeleton and/or we're not supposed to update, then return.
if skeleton_to_use == null:
return
if update_mode >= 3:
return
# Get the bone index.
var bone: int = skeleton_to_use.find_bone(bone_name)
# If no bone is found (-1), then return and optionally printan error.
if bone == -1:
if debug_messages:
print(name, " - IK_LookAt: No bone in skeleton found with name [", bone_name, "]!")
return
# get the bone's global transform pose.
var rest = skeleton_to_use.get_bone_global_pose(bone)
# Convert our position relative to the skeleton's transform.
var target_pos = global_transform.origin * skeleton_to_use.global_transform
# Call helper's look_at function with the chosen up axis.
if look_at_axis == 0:
rest = rest.looking_at(target_pos, Vector3.RIGHT)
elif look_at_axis == 1:
rest = rest.looking_at(target_pos, Vector3.UP)
elif look_at_axis == 2:
rest = rest.looking_at(target_pos, Vector3.FORWARD)
else:
rest = rest.looking_at(target_pos, Vector3.UP)
if debug_messages:
print(name, " - IK_LookAt: Unknown look_at_axis value!")
# Get the rotation euler of the bone and of this node.
var rest_euler = rest.basis.get_euler()
var self_euler = global_transform.basis.orthonormalized().get_euler()
# Flip the rotation euler if using negative rotation.
if use_negative_our_rot:
self_euler = -self_euler
# Apply this node's rotation euler on each axis, if wanted/required.
if use_our_rotation_x:
rest_euler.x = self_euler.x
if use_our_rotation_y:
rest_euler.y = self_euler.y
if use_our_rotation_z:
rest_euler.z = self_euler.z
# Make a new basis with the, potentially, changed euler angles.
rest.basis = Basis.from_euler(rest_euler)
# Apply additional rotation stored in additional_rotation to the bone.
if additional_rotation != Vector3.ZERO:
rest.basis = rest.basis.rotated(rest.basis.x, deg_to_rad(additional_rotation.x))
rest.basis = rest.basis.rotated(rest.basis.y, deg_to_rad(additional_rotation.y))
rest.basis = rest.basis.rotated(rest.basis.z, deg_to_rad(additional_rotation.z))
# If the position is set using an additional bone, then set the origin
# based on that bone and its length.
if position_using_additional_bone:
var additional_bone_id = skeleton_to_use.find_bone(additional_bone_name)
var additional_bone_pos = skeleton_to_use.get_bone_global_pose(additional_bone_id)
rest.origin = (
additional_bone_pos.origin
- additional_bone_pos.basis.z.normalized() * additional_bone_length
)
# Finally, apply the new rotation to the bone in the skeleton.
skeleton_to_use.set_bone_global_pose_override(bone, rest, interpolation, true)
func _setup_for_editor():
# To see the target in the editor, let's create a MeshInstance3D,
# add it as a child of this node, and name it.
_editor_indicator = MeshInstance3D.new()
add_child(_editor_indicator)
_editor_indicator.name = &"(EditorOnly) Visual indicator"
# Make a sphere mesh for the MeshInstance3D
var indicator_mesh = SphereMesh.new()
indicator_mesh.radius = 0.1
indicator_mesh.height = 0.2
indicator_mesh.radial_segments = 8
indicator_mesh.rings = 4
# Create a new StandardMaterial3D for the sphere and give it the editor
# gizmo texture so it is textured.
var indicator_material = StandardMaterial3D.new()
indicator_material.flags_unshaded = true
indicator_material.albedo_texture = preload("editor_gizmo_texture.png")
indicator_material.albedo_color = Color(1, 0.5, 0, 1)
# Assign the material and mesh to the MeshInstance3D.
indicator_mesh.material = indicator_material
_editor_indicator.mesh = indicator_mesh
func _setup_skeleton_path():
if skeleton_path == null:
if debug_messages:
print(name, " - IK_LookAt: No Nodepath selected for skeleton_path!")
return
# Get the node at that location, if there is one.
var temp = get_node(skeleton_path)
if temp != null:
if temp is Skeleton3D:
skeleton_to_use = temp
if debug_messages:
print(name, " - IK_LookAt: attached to (new) skeleton")
else:
skeleton_to_use = null
if debug_messages:
print(name, " - IK_LookAt: skeleton_path does not point to a skeleton!")
else:
if debug_messages:
print(name, " - IK_LookAt: No Nodepath selected for skeleton_path!")
| |
118278
|
[gd_scene load_steps=6 format=3 uid="uid://d36uvu4r5qtpi"]
[ext_resource type="Script" path="res://fps/simple_bullet.gd" id="1"]
[sub_resource type="PhysicsMaterial" id="1"]
bounce = 0.5
[sub_resource type="SphereMesh" id="2"]
[sub_resource type="StandardMaterial3D" id="3"]
albedo_color = Color(0.769531, 0.486969, 0, 1)
emission_enabled = true
emission = Color(1, 0.445313, 0, 1)
emission_energy = 1.8
[sub_resource type="SphereShape3D" id="4"]
radius = 0.4
[node name="SimpleBullet" type="RigidBody3D"]
mass = 2.0
physics_material_override = SubResource( "1" )
gravity_scale = 3.0
continuous_cd = true
can_sleep = false
linear_damp = 0.4
script = ExtResource( "1" )
[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
transform = Transform3D(0.4, 0, 0, 0, 0.4, 0, 0, 0, 0.4, 0, 0, 0)
cast_shadow = 0
mesh = SubResource( "2" )
surface_material_override/0 = SubResource( "3" )
[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
shape = SubResource( "4" )
| |
118282
|
extends RigidBody3D
const DESPAWN_TIME = 5
var timer = 0
func _ready():
set_physics_process(true);
func _physics_process(delta):
timer += delta
if timer > DESPAWN_TIME:
queue_free()
timer = 0
| |
118286
|
[node name="Wall4" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(1, 0, -4.76837e-07, 0, 4, 0, 1.19209e-07, 0, 4, -19.9997, 8.00032, -21.9995)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall4"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall4/StaticBody3D"]
shape = SubResource("6")
[node name="Wall5" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(-1.62921e-07, 0, -4, 0, 4, 0, 1, 0, -6.51683e-07, -9.9997, 8.00032, -27.9995)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall5"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall5/StaticBody3D"]
shape = SubResource("6")
[node name="Wall6" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(-1, 0, 8.26528e-07, 0, 4, 0, -2.06632e-07, 0, -4, 0.000319004, 8.00032, -21.9995)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall6"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall6/StaticBody3D"]
shape = SubResource("6")
[node name="Wall7" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(-1.62921e-07, 0, -4, 0, 4, 0, 1, 0, -6.51683e-07, 10.0003, 8.00032, -15.9995)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall7"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall7/StaticBody3D"]
shape = SubResource("6")
[node name="Wall9" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(1, 0, -4.76837e-07, 0, 4, 0, 1.19209e-07, 0, 4, 25.0003, 8.00032, -25.9995)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall9"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall9/StaticBody3D"]
shape = SubResource("6")
[node name="Wall10" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(0.573577, 0, 3.27661, 0, 4, 0, -0.819152, 0, 2.29431, 23.0003, 8.00032, 3.00049)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall10"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall10/StaticBody3D"]
shape = SubResource("6")
[node name="Wall11" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(-0.819152, 0, 2.29431, 0, 4, 0, -0.573577, 0, -3.27661, 22.2126, 8.00032, 14.7123)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall11"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall11/StaticBody3D"]
shape = SubResource("6")
[node name="Wall12" type="MeshInstance3D" parent="Level/Walls"]
transform = Transform3D(-0.627507, 2.10616, 2.29431, 0.642788, 3.06418, 0, -0.439385, 1.47475, -3.27661, 14.8402, 8.00032, 9.55015)
mesh = SubResource("4")
surface_material_override/0 = SubResource("7")
[node name="StaticBody3D" type="StaticBody3D" parent="Level/Walls/Wall12"]
[node name="CollisionShape3D" type="CollisionShape3D" parent="Level/Walls/Wall12/StaticBody3D"]
shape = SubResource("6")
[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
transform = Transform3D(0.388878, -0.754027, 0.529355, 0, 0.574581, 0.818448, -0.921289, -0.318277, 0.223442, -9.77531, 11.5204, 11.766)
light_color = Color(1, 0.925598, 0.820313, 1)
shadow_enabled = true
directional_shadow_mode = 0
[node name="Control" type="Control" parent="."]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
[node name="Panel" type="Panel" parent="Control"]
modulate = Color(1, 1, 1, 0.784314)
layout_mode = 1
anchors_preset = 12
anchor_top = 1.0
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = -2.0
offset_top = -94.0
offset_right = 4.0
grow_horizontal = 2
grow_vertical = 0
[node name="Label" type="Label" parent="Control/Panel"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
text = "F.A.B.R.I.K IK Example use case: Dynamic FPS Animations
Controls: WASD/Arrows to move, left click to fire, right click to look down sights, Q/E to lean left/right
Escape to free/lock mouse cursor"
horizontal_alignment = 1
[node name="ButtonPrev" type="Button" parent="Control"]
layout_mode = 0
anchor_top = 1.0
anchor_bottom = 1.0
offset_left = 10.0
offset_top = -60.0
offset_right = 129.0
offset_bottom = -10.0
text = "Previous scene"
script = ExtResource("2")
scene_to_change_to = "res://skeleton_ik.tscn"
[node name="Crosshair" type="Control" parent="Control"]
modulate = Color(1, 1, 1, 0.784314)
anchors_preset = 0
anchor_left = 0.5
anchor_top = 0.5
anchor_right = 0.5
anchor_bottom = 0.5
offset_left = -20.0
offset_top = -20.0
offset_right = 20.0
offset_bottom = 20.0
[node name="ColorRect" type="ColorRect" parent="Control/Crosshair"]
layout_mode = 0
offset_left = 19.0
offset_right = 21.0
offset_bottom = 40.0
[node name="ColorRect2" type="ColorRect" parent="Control/Crosshair"]
layout_mode = 0
offset_left = 40.0
offset_top = 18.0
offset_right = 42.0
offset_bottom = 58.0
rotation = 90.0
[node name="CharacterBody3D" type="CharacterBody3D" parent="."]
script = ExtResource("3")
| |
118350
|
extends CharacterBody3D
# Moves the player
@export_range(1, 2) var player_id := 1
@export var walk_speed := 2.0
func _physics_process(_delta: float) -> void:
var move_direction := Input.get_vector(
&"move_left_player" + str(player_id),
&"move_right_player" + str(player_id),
&"move_up_player" + str(player_id),
&"move_down_player" + str(player_id),
)
velocity.x += move_direction.x * walk_speed
velocity.z += move_direction.y * walk_speed
# Apply friction.
velocity *= 0.9
move_and_slide()
| |
118354
|
extends Node3D
# Handle the motion of both player cameras as well as communication with the
# SplitScreen shader to achieve the dynamic split screen effet
#
# Cameras are place on the segment joining the two players, either in the middle
# if players are close enough or at a fixed distance if they are not.
# In the first case, both cameras being at the same location, only the view of
# the first one is used for the entire screen thus allowing the players to play
# on a unsplit screen.
# In the second case, the screen is split in two with a line perpendicular to the
# segement joining the two players.
#
# The points of customization are:
# max_separation: the distance between players at which the view starts to split
# split_line_thickness: the thickness of the split line in pixels
# split_line_color: color of the split line
# adaptive_split_line_thickness: if true, the split line thickness will vary
# depending on the distance between players. If false, the thickness will
# be constant and equal to split_line_thickness
@export var max_separation := 20.0
@export var split_line_thickness := 3.0
@export var split_line_color := Color.BLACK
@export var adaptive_split_line_thickness := true
@onready var player1: CharacterBody3D = $"../Player1"
@onready var player2: CharacterBody3D = $"../Player2"
@onready var view: TextureRect = $View
@onready var viewport1: SubViewport = $Viewport1
@onready var viewport2: SubViewport = $Viewport2
@onready var camera1: Camera3D = viewport1.get_node(^"Camera1")
@onready var camera2: Camera3D = viewport2.get_node(^"Camera2")
var viewport_base_height := int(ProjectSettings.get_setting("display/window/size/viewport_height"))
func _ready() -> void:
_on_size_changed()
_update_splitscreen()
get_viewport().size_changed.connect(_on_size_changed)
view.material.set_shader_parameter("viewport1", viewport1.get_texture())
view.material.set_shader_parameter("viewport2", viewport2.get_texture())
func _process(_delta: float) -> void:
_move_cameras()
_update_splitscreen()
func _move_cameras() -> void:
var position_difference := _get_position_difference_in_world()
var distance := clampf(_get_horizontal_length(position_difference), 0, max_separation)
position_difference = position_difference.normalized() * distance
camera1.position.x = player1.position.x + position_difference.x / 2.0
camera1.position.z = player1.position.z + position_difference.z / 2.0
camera2.position.x = player2.position.x - position_difference.x / 2.0
camera2.position.z = player2.position.z - position_difference.z / 2.0
func _update_splitscreen() -> void:
var screen_size := get_viewport().get_visible_rect().size
var player1_position := camera1.unproject_position(player1.position) / screen_size
var player2_position := camera2.unproject_position(player2.position) / screen_size
var thickness := 0.0
if adaptive_split_line_thickness:
var position_difference := _get_position_difference_in_world()
var distance := _get_horizontal_length(position_difference)
thickness = lerpf(0, split_line_thickness, (distance - max_separation) / max_separation)
thickness = clampf(thickness, 0, split_line_thickness)
else:
thickness = split_line_thickness
view.material.set_shader_parameter("split_active", _is_split_state())
view.material.set_shader_parameter("player1_position", player1_position)
view.material.set_shader_parameter("player2_position", player2_position)
view.material.set_shader_parameter("split_line_thickness", thickness)
view.material.set_shader_parameter("split_line_color", split_line_color)
## Returns `true` if split screen is active (which occurs when players are
## too far apart from each other), `false` otherwise.
## Only the horizontal components (x, z) are used for distance computation.
func _is_split_state() -> bool:
var position_difference := _get_position_difference_in_world()
var separation_distance := _get_horizontal_length(position_difference)
return separation_distance > max_separation
func _on_size_changed() -> void:
var screen_size := get_viewport().get_visible_rect().size
$Viewport1.size = screen_size
$Viewport2.size = screen_size
view.material.set_shader_parameter("viewport_size", screen_size)
func _get_position_difference_in_world() -> Vector3:
return player2.position - player1.position
func _get_horizontal_length(vec: Vector3) -> float:
return Vector2(vec.x, vec.z).length()
| |
118361
|
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group4/Wall5"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group4/Wall5" groups=["walls"]]
material_override = SubResource("33")
mesh = SubResource("11")
[node name="Wall6" type="StaticBody3D" parent="Walls/Group4"]
transform = Transform3D(0.155702, 0, -0.987804, 0, 1, 0, 0.987804, 0, 0.155702, -1.39999, 0.5, -3.24225)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group4/Wall6"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group4/Wall6" groups=["walls"]]
material_override = SubResource("34")
mesh = SubResource("11")
[node name="Group5" type="Node3D" parent="Walls"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 14)
[node name="Wall1" type="StaticBody3D" parent="Walls/Group5"]
transform = Transform3D(0.999549, 0, 0.0300306, 0, 1, 0, -0.0300306, 0, 0.999549, -1.87929, 0.5, -3.04373)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group5/Wall1"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group5/Wall1" groups=["walls"]]
material_override = SubResource("35")
mesh = SubResource("11")
[node name="Wall2" type="StaticBody3D" parent="Walls/Group5"]
transform = Transform3D(0.999549, 0, 0.0300306, 0, 1, 0, -0.0300306, 0, 0.999549, 6.39778, 0.5, -1.68458)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group5/Wall2"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group5/Wall2" groups=["walls"]]
material_override = SubResource("36")
mesh = SubResource("11")
[node name="Wall3" type="StaticBody3D" parent="Walls/Group5"]
transform = Transform3D(0.999549, 0, 0.0300306, 0, 1, 0, -0.0300306, 0, 0.999549, -4.44285, 0.5, -6.669)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group5/Wall3"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group5/Wall3" groups=["walls"]]
material_override = SubResource("37")
mesh = SubResource("11")
[node name="Wall4" type="StaticBody3D" parent="Walls/Group5"]
transform = Transform3D(0.999549, 0, 0.0300306, 0, 1, 0, -0.0300306, 0, 0.999549, -0.234326, 0.5, 2.05526)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group5/Wall4"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group5/Wall4" groups=["walls"]]
material_override = SubResource("38")
mesh = SubResource("11")
[node name="Wall5" type="StaticBody3D" parent="Walls/Group5"]
transform = Transform3D(0.999549, 0, 0.0300306, 0, 1, 0, -0.0300306, 0, 0.999549, 2.17761, 0.5, -4.76423)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group5/Wall5"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group5/Wall5" groups=["walls"]]
material_override = SubResource("39")
mesh = SubResource("11")
[node name="Wall6" type="StaticBody3D" parent="Walls/Group5"]
transform = Transform3D(0.999549, 0, 0.0300306, 0, 1, 0, -0.0300306, 0, 0.999549, -3.21803, 0.5, 0.834073)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group5/Wall6"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group5/Wall6" groups=["walls"]]
material_override = SubResource("40")
mesh = SubResource("11")
[node name="Group6" type="Node3D" parent="Walls"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 10, 0, -7)
[node name="Wall1" type="StaticBody3D" parent="Walls/Group6"]
transform = Transform3D(0.613129, 0, -0.789983, 0, 1, 0, 0.789983, 0, 0.613129, 1.70841, 0.5, -3.54429)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group6/Wall1"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group6/Wall1" groups=["walls"]]
material_override = SubResource("41")
mesh = SubResource("11")
[node name="Wall2" type="StaticBody3D" parent="Walls/Group6"]
transform = Transform3D(0.613129, 0, -0.789983, 0, 1, 0, 0.789983, 0, 0.613129, 5.48642, 0.5, 3.94462)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group6/Wall2"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group6/Wall2" groups=["walls"]]
material_override = SubResource("42")
mesh = SubResource("11")
[node name="Wall3" type="StaticBody3D" parent="Walls/Group6"]
transform = Transform3D(0.613129, 0, -0.789983, 0, 1, 0, 0.789983, 0, 0.613129, 3.1275, 0.5, -7.7515)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group6/Wall3"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group6/Wall3" groups=["walls"]]
material_override = SubResource("43")
mesh = SubResource("11")
[node name="Wall4" type="StaticBody3D" parent="Walls/Group6"]
transform = Transform3D(0.613129, 0, -0.789983, 0, 1, 0, 0.789983, 0, 0.613129, -1.44268, 0.5, 0.788867)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group6/Wall4"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group6/Wall4" groups=["walls"]]
material_override = SubResource("44")
mesh = SubResource("11")
| |
118362
|
[node name="Wall5" type="StaticBody3D" parent="Walls/Group6"]
transform = Transform3D(0.613129, 0, -0.789983, 0, 1, 0, 0.789983, 0, 0.613129, 5.48868, 0.5, -1.27975)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group6/Wall5"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group6/Wall5" groups=["walls"]]
material_override = SubResource("45")
mesh = SubResource("11")
[node name="Wall6" type="StaticBody3D" parent="Walls/Group6"]
transform = Transform3D(0.613129, 0, -0.789983, 0, 1, 0, 0.789983, 0, 0.613129, -2.2137, 0.5, -2.34152)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group6/Wall6"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group6/Wall6" groups=["walls"]]
material_override = SubResource("46")
mesh = SubResource("11")
[node name="Group7" type="Node3D" parent="Walls"]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0, -16)
[node name="Wall1" type="StaticBody3D" parent="Walls/Group7"]
transform = Transform3D(-0.999329, 0, -0.0366257, 0, 1, 0, 0.0366257, 0, -0.999329, 1.73055, 0.5, 2.47421)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group7/Wall1"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group7/Wall1" groups=["walls"]]
material_override = SubResource("47")
mesh = SubResource("11")
[node name="Wall2" type="StaticBody3D" parent="Walls/Group7"]
transform = Transform3D(-0.999329, 0, -0.0366257, 0, 1, 0, 0.0366257, 0, -0.999329, -6.55531, 0.5, 1.16971)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group7/Wall2"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group7/Wall2" groups=["walls"]]
material_override = SubResource("48")
mesh = SubResource("11")
[node name="Wall3" type="StaticBody3D" parent="Walls/Group7"]
transform = Transform3D(-0.999329, 0, -0.0366257, 0, 1, 0, 0.0366257, 0, -0.999329, 4.31798, 0.5, 6.08249)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group7/Wall3"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group7/Wall3" groups=["walls"]]
material_override = SubResource("49")
mesh = SubResource("11")
[node name="Wall4" type="StaticBody3D" parent="Walls/Group7"]
transform = Transform3D(-0.999329, 0, -0.0366257, 0, 1, 0, 0.0366257, 0, -0.999329, 0.0519707, 0.5, -2.61381)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group7/Wall4"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group7/Wall4" groups=["walls"]]
material_override = SubResource("50")
mesh = SubResource("11")
[node name="Wall5" type="StaticBody3D" parent="Walls/Group7"]
transform = Transform3D(-0.999329, 0, -0.0366257, 0, 1, 0, 0.0366257, 0, -0.999329, -2.31492, 0.5, 4.22145)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group7/Wall5"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group7/Wall5" groups=["walls"]]
material_override = SubResource("51")
mesh = SubResource("11")
[node name="Wall6" type="StaticBody3D" parent="Walls/Group7"]
transform = Transform3D(-0.999329, 0, -0.0366257, 0, 1, 0, 0.0366257, 0, -0.999329, 3.04367, 0.5, -1.41234)
[node name="CollisionShape3D" type="CollisionShape3D" parent="Walls/Group7/Wall6"]
shape = SubResource("9")
[node name="MeshInstance3D" type="MeshInstance3D" parent="Walls/Group7/Wall6" groups=["walls"]]
material_override = SubResource("52")
mesh = SubResource("11")
| |
118364
|
extends Node2D
const PAD_SPEED = 150
const INITIAL_BALL_SPEED = 80.0
var ball_speed := INITIAL_BALL_SPEED
var screen_size := Vector2(640, 400)
# Default ball direction.
var direction := Vector2.LEFT
var pad_size := Vector2(8, 32)
@onready var ball: Sprite2D = $Ball
@onready var left_paddle: Sprite2D = $LeftPaddle
@onready var right_paddle: Sprite2D = $RightPaddle
func _ready() -> void:
screen_size = get_viewport_rect().size # Get actual size.
pad_size = left_paddle.get_texture().get_size()
func _process(delta: float) -> void:
# Get ball position and pad rectangles.
var ball_pos := ball.get_position()
var left_rect := Rect2(left_paddle.get_position() - pad_size * 0.5, pad_size)
var right_rect := Rect2(right_paddle.get_position() - pad_size * 0.5, pad_size)
# Integrate new ball postion.
ball_pos += direction * ball_speed * delta
# Flip when touching roof or floor.
if (ball_pos.y < 0 and direction.y < 0) or (ball_pos.y > screen_size.y and direction.y > 0):
direction.y = -direction.y
# Flip, change direction and increase speed when touching pads.
if (left_rect.has_point(ball_pos) and direction.x < 0) or (right_rect.has_point(ball_pos) and direction.x > 0):
direction.x = -direction.x
ball_speed *= 1.1
direction.y = randf() * 2.0 - 1
direction = direction.normalized()
# Check gameover.
if ball_pos.x < 0 or ball_pos.x > screen_size.x:
ball_pos = screen_size * 0.5
ball_speed = INITIAL_BALL_SPEED
direction = Vector2(-1, 0)
ball.set_position(ball_pos)
# Move left pad.
var left_pos := left_paddle.get_position()
if left_pos.y > 0 and Input.is_action_pressed(&"left_move_up"):
left_pos.y += -PAD_SPEED * delta
if left_pos.y < screen_size.y and Input.is_action_pressed(&"left_move_down"):
left_pos.y += PAD_SPEED * delta
left_paddle.set_position(left_pos)
# Move right pad.
var right_pos := right_paddle.get_position()
if right_pos.y > 0 and Input.is_action_pressed(&"right_move_up"):
right_pos.y += -PAD_SPEED * delta
if right_pos.y < screen_size.y and Input.is_action_pressed(&"right_move_down"):
right_pos.y += PAD_SPEED * delta
right_paddle.set_position(right_pos)
| |
118366
|
# 2D in 3D
A demo showing how a 2D scene can be shown within a 3D scene using viewports.
Language: GDScript
Renderer: Compatibility
Check out this demo on the asset library: https://godotengine.org/asset-library/asset/2803
## How does it work?
The Pong game is rendered to a custom
[`Viewport`](https://docs.godotengine.org/en/latest/classes/class_viewport.html)
node rather than the main Viewport. In the code,
`get_texture()` is called on the Viewport to get a
[`ViewportTexture`](https://docs.godotengine.org/en/latest/classes/class_viewporttexture.html),
which is then assigned to the quad's material's albedo texture.
## Screenshots

| |
118377
|
[gd_scene load_steps=11 format=3 uid="uid://xwkspajfdmd7"]
[ext_resource type="Script" path="res://3d_in_2d.gd" id="1"]
[ext_resource type="Texture2D" uid="uid://q5bonn8iowbc" path="res://robot_demo.png" id="2"]
[ext_resource type="PackedScene" uid="uid://8nlipuu0ceal" path="res://robot_3d.tscn" id="3"]
[sub_resource type="ViewportTexture" id="ViewportTexture_2squv"]
viewport_path = NodePath("SubViewport")
[sub_resource type="AtlasTexture" id="2"]
atlas = ExtResource("2")
region = Rect2(0, 0, 64, 64)
[sub_resource type="AtlasTexture" id="3"]
atlas = ExtResource("2")
region = Rect2(64, 0, 64, 64)
[sub_resource type="AtlasTexture" id="4"]
atlas = ExtResource("2")
region = Rect2(128, 0, 64, 64)
[sub_resource type="AtlasTexture" id="5"]
atlas = ExtResource("2")
region = Rect2(192, 0, 64, 64)
[sub_resource type="AtlasTexture" id="6"]
atlas = ExtResource("2")
region = Rect2(256, 0, 64, 64)
[sub_resource type="SpriteFrames" id="7"]
animations = [{
"frames": [{
"duration": 1.0,
"texture": SubResource("2")
}, {
"duration": 1.0,
"texture": SubResource("3")
}, {
"duration": 1.0,
"texture": SubResource("4")
}, {
"duration": 1.0,
"texture": SubResource("5")
}, {
"duration": 1.0,
"texture": SubResource("6")
}],
"loop": true,
"name": &"default",
"speed": 5.0
}]
[node name="3Din2D" type="Node2D"]
script = ExtResource("1")
[node name="SubViewport" type="SubViewport" parent="."]
transparent_bg = true
msaa_3d = 2
size = Vector2i(300, 300)
render_target_update_mode = 4
[node name="Robot3D" parent="SubViewport" instance=ExtResource("3")]
[node name="ViewportSprite" type="Sprite2D" parent="."]
position = Vector2(650, 300)
texture = SubResource("ViewportTexture_2squv")
[node name="AnimatedSprite2D" type="AnimatedSprite2D" parent="."]
texture_filter = 1
position = Vector2(350, 300)
scale = Vector2(3, 3)
sprite_frames = SubResource("7")
[node name="Camera2D" type="Camera2D" parent="."]
offset = Vector2(512, 300)
| |
118379
|
# 3D in 2D
A demo showing how a 3D scene can be shown within a 2D one using viewports.
Language: GDScript
Renderer: Compatibility
Check out this demo on the asset library: https://godotengine.org/asset-library/asset/2804
## How does it work?
The 3D robot is rendered to a custom
[`Viewport`](https://docs.godotengine.org/en/latest/classes/class_viewport.html)
node rather than the main Viewport. In the code,
`get_texture()` is called on the Viewport to get a
[`ViewportTexture`](https://docs.godotengine.org/en/latest/classes/class_viewporttexture.html),
which is then assigned to the sprite's texture.
## Screenshots

| |
118382
|
extends Node2D
@onready var viewport: SubViewport = $SubViewport
@onready var viewport_initial_size: Vector2i = viewport.size
@onready var viewport_sprite: Sprite2D = $ViewportSprite
func _ready() -> void:
$AnimatedSprite2D.play()
get_viewport().size_changed.connect(_root_viewport_size_changed)
# Called when the root's viewport size changes (i.e. when the window is resized).
# This is done to handle multiple resolutions without losing quality.
func _root_viewport_size_changed() -> void:
# The viewport is resized depending on the window height.
# To compensate for the larger resolution, the viewport sprite is scaled down.
viewport.size = Vector2.ONE * get_viewport().size.y
viewport_sprite.scale = Vector2.ONE * viewport_initial_size.y / get_viewport().size.y
| |
118391
|
extends Node3D
## Used for checking if the mouse is inside the Area3D.
var is_mouse_inside := false
## The last processed input touch/mouse event. Used to calculate relative movement.
var last_event_pos2D := Vector2()
## The time of the last event in seconds since engine start.
var last_event_time := -1.0
@onready var node_viewport: SubViewport = $SubViewport
@onready var node_quad: MeshInstance3D = $Quad
@onready var node_area: Area3D = $Quad/Area3D
func _ready() -> void:
node_area.mouse_entered.connect(_mouse_entered_area)
node_area.mouse_exited.connect(_mouse_exited_area)
node_area.input_event.connect(_mouse_input_event)
# If the material is NOT set to use billboard settings, then avoid running billboard specific code
if node_quad.get_surface_override_material(0).billboard_mode == BaseMaterial3D.BillboardMode.BILLBOARD_DISABLED:
set_process(false)
func _process(_delta: float) -> void:
# NOTE: Remove this function if you don't plan on using billboard settings.
rotate_area_to_billboard()
func _mouse_entered_area() -> void:
is_mouse_inside = true
func _mouse_exited_area() -> void:
is_mouse_inside = false
func _unhandled_input(event: InputEvent) -> void:
# Check if the event is a non-mouse/non-touch event
for mouse_event in [InputEventMouseButton, InputEventMouseMotion, InputEventScreenDrag, InputEventScreenTouch]:
if is_instance_of(event, mouse_event):
# If the event is a mouse/touch event, then we can ignore it here, because it will be
# handled via Physics Picking.
return
node_viewport.push_input(event)
func _mouse_input_event(_camera: Camera3D, event: InputEvent, event_position: Vector3, _normal: Vector3, _shape_idx: int) -> void:
# Get mesh size to detect edges and make conversions. This code only supports PlaneMesh and QuadMesh.
var quad_mesh_size: Vector2 = node_quad.mesh.size
# Event position in Area3D in world coordinate space.
var event_pos3D := event_position
# Current time in seconds since engine start.
var now := Time.get_ticks_msec() / 1000.0
# Convert position to a coordinate space relative to the Area3D node.
# NOTE: `affine_inverse()` accounts for the Area3D node's scale, rotation, and position in the scene!
event_pos3D = node_quad.global_transform.affine_inverse() * event_pos3D
# TODO: Adapt to bilboard mode or avoid completely.
var event_pos2D := Vector2()
if is_mouse_inside:
# Convert the relative event position from 3D to 2D.
event_pos2D = Vector2(event_pos3D.x, -event_pos3D.y)
# Right now the event position's range is the following: (-quad_size/2) -> (quad_size/2)
# We need to convert it into the following range: -0.5 -> 0.5
event_pos2D.x = event_pos2D.x / quad_mesh_size.x
event_pos2D.y = event_pos2D.y / quad_mesh_size.y
# Then we need to convert it into the following range: 0 -> 1
event_pos2D.x += 0.5
event_pos2D.y += 0.5
# Finally, we convert the position to the following range: 0 -> viewport.size
event_pos2D.x *= node_viewport.size.x
event_pos2D.y *= node_viewport.size.y
# We need to do these conversions so the event's position is in the viewport's coordinate system.
elif last_event_pos2D != null:
# Fall back to the last known event position.
event_pos2D = last_event_pos2D
# Set the event's position and global position.
event.position = event_pos2D
if event is InputEventMouse:
event.global_position = event_pos2D
# Calculate the relative event distance.
if event is InputEventMouseMotion or event is InputEventScreenDrag:
# If there is not a stored previous position, then we'll assume there is no relative motion.
if last_event_pos2D == null:
event.relative = Vector2(0, 0)
# If there is a stored previous position, then we'll calculate the relative position by subtracting
# the previous position from the new position. This will give us the distance the event traveled from prev_pos.
else:
event.relative = event_pos2D - last_event_pos2D
event.velocity = event.relative / (now - last_event_time)
# Update last_event_pos2D with the position we just calculated.
last_event_pos2D = event_pos2D
# Update last_event_time to current time.
last_event_time = now
# Finally, send the processed input event to the viewport.
node_viewport.push_input(event)
func rotate_area_to_billboard() -> void:
var billboard_mode: BaseMaterial3D.BillboardMode = node_quad.get_surface_override_material(0).billboard_mode
# Try to match the area with the material's billboard setting, if enabled.
if billboard_mode > 0:
# Get the camera.
var camera := get_viewport().get_camera_3d()
# Look in the same direction as the camera.
var look := camera.to_global(Vector3(0, 0, -100)) - camera.global_transform.origin
look = node_area.position + look
# Y-Billboard: Lock Y rotation, but gives bad results if the camera is tilted.
if billboard_mode == 2:
look = Vector3(look.x, 0, look.z)
node_area.look_at(look, Vector3.UP)
# Rotate in the Z axis to compensate camera tilt.
node_area.rotate_object_local(Vector3.BACK, camera.rotation.z)
| |
118421
|
extends VBoxContainer
func _ready() -> void:
# Don't allow loading files that don't exist yet.
($SaveLoad/LoadConfigFile as Button).disabled = not FileAccess.file_exists("user://save_config_file.ini")
($SaveLoad/LoadJSON as Button).disabled = not FileAccess.file_exists("user://save_json.json")
func _on_open_user_data_folder_pressed() -> void:
OS.shell_open(ProjectSettings.globalize_path("user://"))
| |
118429
|
extends Button
# This script shows how to save data using Godot's custom ConfigFile format.
# ConfigFile can store any Variant type except Signal or Callable.
# It can even store Objects, but be extra careful where you deserialize them
# from, because they can include (potentially malicious) scripts.
const SAVE_PATH = "user://save_config_file.ini"
## The root game node (so we can get and instance enemies).
@export var game_node: NodePath
## The player node (so we can set/get its health and position).
@export var player_node: NodePath
func save_game() -> void:
var config := ConfigFile.new()
var player := get_node(player_node) as Player
config.set_value("player", "position", player.position)
config.set_value("player", "health", player.health)
config.set_value("player", "rotation", player.sprite.rotation)
var enemies := []
for enemy in get_tree().get_nodes_in_group(&"enemy"):
enemies.push_back({
position = enemy.position,
})
config.set_value("enemies", "enemies", enemies)
config.save(SAVE_PATH)
($"../LoadConfigFile" as Button).disabled = false
func load_game() -> void:
var config := ConfigFile.new()
config.load(SAVE_PATH)
var player := get_node(player_node) as Player
player.position = config.get_value("player", "position")
player.health = config.get_value("player", "health")
player.sprite.rotation = config.get_value("player", "rotation")
# Remove existing enemies before adding new ones.
get_tree().call_group("enemy", "queue_free")
var enemies: Array = config.get_value("enemies", "enemies")
var game := get_node(game_node)
for enemy_config: Dictionary in enemies:
var enemy := preload("res://enemy.tscn").instantiate() as Enemy
enemy.position = enemy_config.position
game.add_child(enemy)
| |
118434
|
extends Panel
func _on_goto_scene_pressed() -> void:
# Change the scene to the one located at the given path.
get_tree().change_scene_to_file("res://scene_b.tscn")
| |
118436
|
extends Panel
func _on_goto_scene_pressed() -> void:
# Change the scene to the given PackedScene.
# Though it usually takes more code, this can have advantages, such as letting you load the
# scene in another thread, or use a scene that isn't saved to a file.
var scene: PackedScene = load("res://scene_a.tscn")
get_tree().change_scene_to_packed(scene)
| |
118439
|
; Engine configuration file.
; It's best edited using the editor UI and not directly,
; since the parameters that go here are not all obvious.
;
; Format:
; [section] ; section goes between []
; param=value ; assign values to parameters
config_version=5
[application]
config/name="Scene Changer"
config/description="This uses functions in SceneTree to switch between two scenes."
config/tags=PackedStringArray("demo", "official")
run/main_scene="res://scene_a.tscn"
config/features=PackedStringArray("4.2")
run/low_processor_mode=true
config/icon="res://icon.svg"
[debug]
gdscript/warnings/untyped_declaration=1
[display]
window/stretch/mode="canvas_items"
window/stretch/aspect="expand"
window/vsync/vsync_mode=0
[rendering]
renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility"
| |
118454
|
extends Control
var thread: Thread
func _on_load_pressed() -> void:
if is_instance_valid(thread) and thread.is_started():
# If a thread is already running, let it finish before we start another.
thread.wait_to_finish()
thread = Thread.new()
print_rich("[b]Starting thread.")
# Our method needs an argument, so we pass it using bind().
thread.start(_bg_load.bind("res://mona.png"))
func _bg_load(path: String) -> Texture2D:
print("Calling thread function.")
var tex := load(path)
# call_deferred() tells the main thread to call a method during idle time.
# Our method operates on nodes currently in the tree, so it isn't safe to
# call directly from another thread.
_bg_load_done.call_deferred()
return tex
func _bg_load_done() -> void:
# Wait for the thread to complete, and get the returned value.
var tex: Texture2D = thread.wait_to_finish()
print_rich("[b][i]Thread finished.\n")
$TextureRect.texture = tex
# We're done with the thread now, so we can free it.
# Threads are reference counted, so this is how we free them.
thread = null
func _exit_tree() -> void:
# You should always wait for a thread to finish before letting it get freed!
# It might not clean up correctly if you don't.
if is_instance_valid(thread) and thread.is_started():
thread.wait_to_finish()
thread = null
| |
118462
|
extends Node
# Changing scenes is most easily done using the `change_scene_to_file()` and
# `change_scene_to_packed()` methods of SceneTree. This script demonstrates
# how to change scenes without those helpers.
func goto_scene(path: String) -> void:
# This function will usually be called from a signal callback,
# or some other function from the running scene.
# Deleting the current scene at this point might be
# a bad idea, because it may be inside of a callback or function of it.
# The worst case will be a crash or unexpected behavior.
# The way around this is deferring the load to a later time, when
# it is ensured that no code from the current scene is running:
_deferred_goto_scene.call_deferred(path)
func _deferred_goto_scene(path: String) -> void:
# Immediately free the current scene. There is no risk here because the
# call to this method is already deferred.
get_tree().current_scene.free()
var packed_scene: PackedScene = ResourceLoader.load(path)
var instanced_scene := packed_scene.instantiate()
# Add it to the scene tree, as direct child of root
get_tree().root.add_child(instanced_scene)
# Set it as the current scene, only after it has been added to the tree
get_tree().current_scene = instanced_scene
| |
118498
|
extends Control
@onready var client: Node = $Client
@onready var host: LineEdit = $VBoxContainer/Connect/Host
@onready var room: LineEdit = $VBoxContainer/Connect/RoomSecret
@onready var mesh: CheckBox = $VBoxContainer/Connect/Mesh
func _ready() -> void:
client.lobby_joined.connect(_lobby_joined)
client.lobby_sealed.connect(_lobby_sealed)
client.connected.connect(_connected)
client.disconnected.connect(_disconnected)
multiplayer.connected_to_server.connect(_mp_server_connected)
multiplayer.connection_failed.connect(_mp_server_disconnect)
multiplayer.server_disconnected.connect(_mp_server_disconnect)
multiplayer.peer_connected.connect(_mp_peer_connected)
multiplayer.peer_disconnected.connect(_mp_peer_disconnected)
@rpc("any_peer", "call_local")
func ping(argument: float) -> void:
_log("[Multiplayer] Ping from peer %d: arg: %f" % [multiplayer.get_remote_sender_id(), argument])
func _mp_server_connected() -> void:
_log("[Multiplayer] Server connected (I am %d)" % client.rtc_mp.get_unique_id())
func _mp_server_disconnect() -> void:
_log("[Multiplayer] Server disconnected (I am %d)" % client.rtc_mp.get_unique_id())
func _mp_peer_connected(id: int) -> void:
_log("[Multiplayer] Peer %d connected" % id)
func _mp_peer_disconnected(id: int) -> void:
_log("[Multiplayer] Peer %d disconnected" % id)
func _connected(id: int, use_mesh: bool) -> void:
_log("[Signaling] Server connected with ID: %d. Mesh: %s" % [id, use_mesh])
func _disconnected() -> void:
_log("[Signaling] Server disconnected: %d - %s" % [client.code, client.reason])
func _lobby_joined(lobby: String) -> void:
_log("[Signaling] Joined lobby %s" % lobby)
func _lobby_sealed() -> void:
_log("[Signaling] Lobby has been sealed")
func _log(msg: String) -> void:
print(msg)
$VBoxContainer/TextEdit.text += str(msg) + "\n"
func _on_peers_pressed() -> void:
_log(str(multiplayer.get_peers()))
func _on_ping_pressed() -> void:
ping.rpc(randf())
func _on_seal_pressed() -> void:
client.seal_lobby()
func _on_start_pressed() -> void:
client.start(host.text, room.text, mesh.button_pressed)
func _on_stop_pressed() -> void:
client.stop()
| |
118511
|
[gd_scene load_steps=3 format=3 uid="uid://c5m3rogpaglk1"]
[ext_resource type="Texture2D" uid="uid://bdomqql6y50po" path="res://brickfloor.png" id="1"]
[sub_resource type="RectangleShape2D" id="1"]
size = Vector2(48, 48)
[node name="TileScene" type="Node2D"]
[node name="Wall" type="Sprite2D" parent="."]
position = Vector2(24, 24)
texture = ExtResource("1")
region_rect = Rect2(0, 0, 48, 48)
[node name="StaticBody2D" type="StaticBody2D" parent="Wall"]
[node name="CollisionShape2D" type="CollisionShape2D" parent="Wall/StaticBody2D"]
shape = SubResource("1")
[node name="Floor" type="Sprite2D" parent="."]
position = Vector2(72, 24)
texture = ExtResource("1")
region_rect = Rect2(48, 0, 48, 48)
| |
118581
|
extends CharacterBody3D
# Settings to control the character.
@export var rotation_speed := 1.0
@export var movement_speed := 5.0
@export var movement_acceleration := 5.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity := float(ProjectSettings.get_setting("physics/3d/default_gravity"))
# Helper variables to keep our code readable.
@onready var origin_node: XROrigin3D = $XROrigin3D
@onready var camera_node: XRCamera3D = $XROrigin3D/XRCamera3D
@onready var neck_position_node: Node3D = $XROrigin3D/XRCamera3D/Neck
@onready var black_out: Node3D = $XROrigin3D/XRCamera3D/BlackOut
## Called when the user has requested their view to be recentered.
func recenter() -> void:
# The code here assumes the player has walked into an area they shouldn't be
# and we return the player back to the character body.
# But other strategies can be applied here as well such as returning the player
# to a starting position or a checkpoint.
# Calculate where our camera should be, we start with our global transform.
var new_camera_transform : Transform3D = global_transform
# Set to the height of our neck joint.
new_camera_transform.origin.y = neck_position_node.global_position.y
# Apply transform our our next position to get our desired camera transform.
new_camera_transform = new_camera_transform * neck_position_node.transform.inverse()
# Remove tilt from camera transform.
var camera_transform : Transform3D = camera_node.transform
var forward_dir : Vector3 = camera_transform.basis.z
forward_dir.y = 0.0
camera_transform = camera_transform.looking_at(camera_transform.origin + forward_dir.normalized(), Vector3.UP, true)
# Update our XR location.
origin_node.global_transform = new_camera_transform * camera_transform.inverse()
# Returns our move input by querying the move action on each controller.
func _get_movement_input() -> Vector2:
var movement := Vector2()
# If move is not bound to one of our controllers,
# that controller will return `Vector2.ZERO`.
movement += $XROrigin3D/LeftHand.get_vector2("move")
movement += $XROrigin3D/RightHand.get_vector2("move")
return movement
# `_process_on_physical_movement()` handles the physical movement of the player
# adjusting our character body position to "catch up to" the player.
# If the character body encounters an obstruction our view will black out
# and we will stop further character movement until the player physically
# moves back.
func _process_on_physical_movement(delta: float) -> bool:
# Remember our current velocity, as we'll apply that later.
var current_velocity := velocity
# Start by rotating the player to face the same way our real player is.
var camera_basis: Basis = origin_node.transform.basis * camera_node.transform.basis
var forward: Vector2 = Vector2(camera_basis.z.x, camera_basis.z.z)
var angle: float = forward.angle_to(Vector2(0.0, 1.0))
# Rotate our character body.
transform.basis = transform.basis.rotated(Vector3.UP, angle)
# Reverse this rotation our origin node.
origin_node.transform = Transform3D().rotated(Vector3.UP, -angle) * origin_node.transform
# Now apply movement, first move our player body to the right location.
var org_player_body: Vector3 = global_transform.origin
var player_body_location: Vector3 = origin_node.transform * camera_node.transform * neck_position_node.transform.origin
player_body_location.y = 0.0
player_body_location = global_transform * player_body_location
velocity = (player_body_location - org_player_body) / delta
move_and_slide()
# Now move our XROrigin back.
var delta_movement := global_transform.origin - org_player_body
origin_node.global_transform.origin -= delta_movement
# Negate any height change in local space due to player hitting ramps, etc.
origin_node.transform.origin.y = 0.0
# Return our value.
velocity = current_velocity
# Check if we managed to move where we wanted to.
var location_offset := (player_body_location - global_transform.origin).length()
if location_offset > 0.1:
# We couldn't go where we wanted to, black out our screen.
black_out.fade = clampf((location_offset - 0.1) / 0.1, 0.0, 1.0)
return true
else:
black_out.fade = 0.0
return false
# `_process_movement_on_input()` handles movement through controller input.
# We first handle rotating the player and then apply movement.
# We also apply the effects of gravity at this point.
func _process_movement_on_input(is_colliding: bool, delta: float) -> void:
if not is_colliding:
# Only handle input if we've not physically moved somewhere we shouldn't.
var movement_input := _get_movement_input()
# First handle rotation, to keep this example simple we are implementing
# "smooth" rotation here. This can lead to motion sickness.
# Adding a comfort option with "stepped" rotation is good practice but
# falls outside of the scope of this demonstration.
rotation.y += -movement_input.x * delta * rotation_speed
# Now handle forward/backwards movement.
# Straffing can be added by using the movement_input.x input
# and using a different input for rotational control.
# Straffing is more prone to motion sickness.
var direction := global_transform.basis * Vector3(0.0, 0.0, -movement_input.y) * movement_speed
if direction:
velocity.x = move_toward(velocity.x, direction.x, delta * movement_acceleration)
velocity.z = move_toward(velocity.z, direction.z, delta * movement_acceleration)
else:
velocity.x = move_toward(velocity.x, 0, delta * movement_acceleration)
velocity.z = move_toward(velocity.z, 0, delta * movement_acceleration)
# Always handle gravity
velocity.y -= gravity * delta
move_and_slide()
# `_physics_process()` handles our player movement.
func _physics_process(delta: float) -> void:
var is_colliding := _process_on_physical_movement(delta)
_process_movement_on_input(is_colliding, delta)
| |
118598
|
extends XROrigin3D
# Settings to control the character.
@export var rotation_speed := 1.0
@export var movement_speed := 5.0
@export var movement_acceleration := 5.0
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity := float(ProjectSettings.get_setting("physics/3d/default_gravity"))
# Helper variables to keep our code readable.
@onready var character_body : CharacterBody3D = $CharacterBody3D
@onready var camera_node : XRCamera3D = $XRCamera3D
@onready var neck_position_node : Node3D = $XRCamera3D/Neck
@onready var black_out : Node3D = $XRCamera3D/BlackOut
## Called when the user has requested their view to be recentered.
func recenter() -> void:
# The code here assumes the player has walked into an area they shouldn't be
# and we return the player back to the character body.
# But other strategies can be applied here as well such as returning the player
# to a starting position or a checkpoint.
# Calculate where our camera should be, we start with our global transform.
var new_camera_transform: Transform3D = character_body.global_transform
# Set to the height of our neck joint.
new_camera_transform.origin.y = neck_position_node.global_position.y
# Apply transform our our next position to get our desired camera transform.
new_camera_transform = new_camera_transform * neck_position_node.transform.inverse()
# Remove tilt from camera transform.
var camera_transform: Transform3D = camera_node.transform
var forward_dir: Vector3 = camera_transform.basis.z
forward_dir.y = 0.0
camera_transform = camera_transform.looking_at(camera_transform.origin + forward_dir.normalized(), Vector3.UP, true)
# Update our XR location.
global_transform = new_camera_transform * camera_transform.inverse()
# Recenter character body.
character_body.transform = Transform3D()
# `_get_movement_input()` returns our move input by querying the move action on each controller.
func _get_movement_input() -> Vector2:
var movement : Vector2 = Vector2()
# If move is not bound to one of our controllers,
# that controller will return `Vector2.ZERO`.
movement += $LeftHand.get_vector2("move")
movement += $RightHand.get_vector2("move")
return movement
# `_process_on_physical_movement` handles the physical movement of the player
# adjusting our character body position to "catch up to" the player.
# If the character body encounters an obstruction our view will black out
# and we will stop further character movement until the player physically
# moves back.
func _process_on_physical_movement(delta: float) -> bool:
# Remember our current velocity, as we'll apply that later.
var current_velocity := character_body.velocity
# Remember where our player body currently is.
var org_player_body: Vector3 = character_body.global_transform.origin
# Determine where our player body should be.
var player_body_location: Vector3 = camera_node.transform * neck_position_node.transform.origin
player_body_location.y = 0.0
player_body_location = global_transform * player_body_location
# Attempt to move our character.
character_body.velocity = (player_body_location - org_player_body) / delta
character_body.move_and_slide()
# Set back to our current value.
character_body.velocity = current_velocity
# Check if we managed to move all the way, ignoring height change.
var movement_left := player_body_location - character_body.global_transform.origin
movement_left.y = 0.0
# Check if we managed to move where we wanted to.
var location_offset := movement_left.length()
if location_offset > 0.1:
# We couldn't go where we wanted to, black out our screen.
black_out.fade = clamp((location_offset - 0.1) / 0.1, 0.0, 1.0)
return true
else:
black_out.fade = 0.0
return false
func _copy_player_rotation_to_character_body() -> void:
# We only copy our forward direction to our character body, we ignore tilt.
var camera_forward := -camera_node.global_transform.basis.z
var body_forward := Vector3(camera_forward.x, 0.0, camera_forward.z)
character_body.global_transform.basis = Basis.looking_at(body_forward, Vector3.UP)
# `_process_movement_on_input` handles movement through controller input.
# We first handle rotating the player and then apply movement.
# We also apply the effects of gravity at this point.
func _process_movement_on_input(is_colliding: bool, delta: float) -> void:
# Remember where our player body currently is.
var org_player_body: Vector3 = character_body.global_transform.origin
if not is_colliding:
# Only handle input if we've not physically moved somewhere we shouldn't.
var movement_input := _get_movement_input()
# First handle rotation, to keep this example simple we are implementing
# "smooth" rotation here. This can lead to motion sickness.
# Adding a comfort option with "stepped" rotation is good practice but
# falls outside of the scope of this demonstration.
var t1 := Transform3D()
var t2 := Transform3D()
var rot := Transform3D()
# We are going to rotate the origin around the player.
var player_position := character_body.global_transform.origin - global_transform.origin
t1.origin = -player_position
t2.origin = player_position
rot = rot.rotated(Vector3(0.0, 1.0, 0.0), -movement_input.x * delta * rotation_speed)
global_transform = (global_transform * t2 * rot * t1).orthonormalized()
# Now ensure our player body is facing the correct way as well.
_copy_player_rotation_to_character_body()
# Now handle forward/backwards movement.
# Straffing can be added by using the movement_input.x input
# and using a different input for rotational control.
# Straffing is more prone to motion sickness.
var direction: Vector3 = (character_body.global_transform.basis * Vector3(0.0, 0.0, -movement_input.y)) * movement_speed
if direction:
character_body.velocity.x = move_toward(character_body.velocity.x, direction.x, delta * movement_acceleration)
character_body.velocity.z = move_toward(character_body.velocity.z, direction.z, delta * movement_acceleration)
else:
character_body.velocity.x = move_toward(character_body.velocity.x, 0, delta * movement_acceleration)
character_body.velocity.z = move_toward(character_body.velocity.z, 0, delta * movement_acceleration)
# Always handle gravity.
character_body.velocity.y -= gravity * delta
# Attempt to move our player.
character_body.move_and_slide()
# And now apply the actual movement to our origin.
global_transform.origin += character_body.global_transform.origin - org_player_body
# _physics_process handles our player movement.
func _physics_process(delta: float) -> void:
var is_colliding := _process_on_physical_movement(delta)
_process_movement_on_input(is_colliding, delta)
| |
118625
|
extends RigidBody3D
class_name PickupAbleBody3D
var highlight_material : Material = preload("res://shaders/highlight_material.tres")
var picked_up_by : Area3D
var closest_areas : Array
var original_parent : Node3D
var tween : Tween
# Called when this object becomes the closest body in an area
func add_is_closest(area : Area3D) -> void:
if not closest_areas.has(area):
closest_areas.push_back(area)
_update_highlight()
# Called when this object becomes the closest body in an area
func remove_is_closest(area : Area3D) -> void:
if closest_areas.has(area):
closest_areas.erase(area)
_update_highlight()
# Returns whether we have been picked up.
func is_picked_up() -> bool:
# If we have a valid picked up by object,
# we've been picked up
if picked_up_by:
return true
return false
# Pick this object up.
func pick_up(pick_up_by) -> void:
# Already picked up? Can't pick up twice.
if picked_up_by:
if picked_up_by == pick_up_by:
return
let_go()
# Remember some state we want to reapply on release.
original_parent = get_parent()
var current_transform = global_transform
# Remove us from our old parent.
original_parent.remove_child(self)
# Process our pickup.
picked_up_by = pick_up_by
picked_up_by.add_child(self)
global_transform = current_transform
freeze = true
# Kill any existing tween and create a new one.
if tween:
tween.kill()
tween = create_tween()
# Snap the object to this transform.
var snap_to : Transform3D
# Add code here to determine snap position and orientation.
# Now tween
tween.tween_property(self, "transform", snap_to, 0.1)
# Let this object go.
func let_go() -> void:
# Ignore if we haven't been picked up.
if not picked_up_by:
return
# Cancel any ongoing tween
if tween:
tween.kill()
tween = null
# Remember our current transform.
var current_transform = global_transform
# Remove us from what picked us up.
picked_up_by.remove_child(self)
picked_up_by = null
# Reset some state.
original_parent.add_child(self)
global_transform = current_transform
freeze = false
# Update our highlight to show that we can be picked up
func _update_highlight() -> void:
if not picked_up_by and not closest_areas.is_empty():
# add highlight
for child in get_children():
if child is MeshInstance3D:
var mesh_instance : MeshInstance3D = child
mesh_instance.material_overlay = highlight_material
else:
# remove highlight
for child in get_children():
if child is MeshInstance3D:
var mesh_instance : MeshInstance3D = child
mesh_instance.material_overlay = null
| |
118626
|
[gd_scene load_steps=3 format=3 uid="uid://byif52d1xkl3u"]
[ext_resource type="Script" path="res://pickup/pickup_handler.gd" id="1_5qec3"]
[sub_resource type="SphereShape3D" id="SphereShape3D_i5on0"]
resource_local_to_scene = true
margin = 0.001
radius = 0.3
[node name="PickupHandler" type="Area3D"]
script = ExtResource("1_5qec3")
pickup_action = null
[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
shape = SubResource("SphereShape3D_i5on0")
[connection signal="body_entered" from="." to="." method="_on_body_entered"]
[connection signal="body_exited" from="." to="." method="_on_body_exited"]
| |
118627
|
@tool
extends Area3D
class_name PickupHandler3D
# This area3D class detects all physics bodys based on
# PickupAbleBody3D within range and handles the logic
# for selecting the closest one and allowing pickup
# of that object.
# Detect range specifies within what radius we detect
# objects we can pick up.
@export var detect_range : float = 0.3:
set(value):
detect_range = value
if is_inside_tree():
_update_detect_range()
_update_closest_body()
# Pickup Action specifies the action in the OpenXR
# action map that triggers our pickup function.
@export var pickup_action : String = "pickup"
var closest_body : PickupAbleBody3D
var picked_up_body: PickupAbleBody3D
var was_pickup_pressed : bool = false
# Update our detection range.
func _update_detect_range() -> void:
var shape : SphereShape3D = $CollisionShape3D.shape
if shape:
shape.radius = detect_range
# Update our closest body.
func _update_closest_body() -> void:
# Do not do this when we're in the editor.
if Engine.is_editor_hint():
return
# Do not check this if we've picked something up.
if picked_up_body:
if closest_body:
closest_body.remove_is_closest(self)
closest_body = null
return
# Find the body that is currently the closest.
var new_closest_body : PickupAbleBody3D
var closest_distance : float = 1000000.0
for body in get_overlapping_bodies():
if body is PickupAbleBody3D and not body.is_picked_up():
var distance_squared = (body.global_position - global_position).length_squared()
if distance_squared < closest_distance:
new_closest_body = body
closest_distance = distance_squared
# Unchanged? Just exit
if closest_body == new_closest_body:
return
# We had a closest body
if closest_body:
closest_body.remove_is_closest(self)
closest_body = new_closest_body
if closest_body:
closest_body.add_is_closest(self)
# Get our controller that we are a child of
func _get_parent_controller() -> XRController3D:
var parent : Node = get_parent()
while parent:
if parent is XRController3D:
return parent
parent = parent.get_parent()
return null
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
_update_detect_range()
_update_closest_body()
# Called every physics frame
func _physics_process(delta) -> void:
# As we move our hands we need to check if the closest body
# has changed.
_update_closest_body()
# Check if our pickup action is true
var pickup_pressed = false
var controller : XRController3D = _get_parent_controller()
if controller:
# While OpenXR can return this as a boolean, there is a lot of
# difference in handling thresholds between platforms.
# So we implement our own logic here.
var pickup_value : float = controller.get_float(pickup_action)
var threshold : float = 0.4 if was_pickup_pressed else 0.6
pickup_pressed = pickup_value > threshold
# Do we need to let go?
if picked_up_body and not pickup_pressed:
picked_up_body.let_go()
picked_up_body = null
# Do we need to pick something up
if not picked_up_body and not was_pickup_pressed and pickup_pressed and closest_body:
picked_up_body = closest_body
picked_up_body.pick_up(self)
# Remember our state for the next frame
was_pickup_pressed = pickup_pressed
| |
118629
|
[gd_resource type="Shader" format=3 uid="uid://cs1jlvgrhd4ac"]
[resource]
code = "// NOTE: Shader automatically converted from Godot Engine 4.3.beta1's StandardMaterial3D.
shader_type spatial;
render_mode blend_mix, depth_draw_opaque, cull_front, diffuse_burley, specular_schlick_ggx, unshaded;
uniform vec4 albedo : source_color;
uniform float grow : hint_range(-16.0, 16.0, 0.001);
uniform float specular : hint_range(0.0, 1.0, 0.01);
uniform float metallic : hint_range(0.0, 1.0, 0.01);
uniform float roughness : hint_range(0.0, 1.0);
void vertex() {
// Standard grow along the normal will create seams
VERTEX += normalize(VERTEX) * grow;
}
void fragment() {
ALBEDO = albedo.rgb;
METALLIC = metallic;
SPECULAR = specular;
ROUGHNESS = roughness;
}
"
| |
118651
|
[gd_scene load_steps=5 format=3 uid="uid://cenb0bfok13vx"]
[ext_resource type="Script" path="res://ui.gd" id="1_wnf2v"]
[ext_resource type="Shader" path="res://cursor.gdshader" id="2_hngl5"]
[sub_resource type="LabelSettings" id="LabelSettings_cnxo1"]
font_size = 64
[sub_resource type="ShaderMaterial" id="ShaderMaterial_84eui"]
shader = ExtResource("2_hngl5")
shader_parameter/color = Color(1, 1, 1, 1)
[node name="UI" type="Control"]
custom_minimum_size = Vector2(1024, 512)
layout_mode = 3
anchors_preset = 0
offset_right = 40.0
offset_bottom = 40.0
script = ExtResource("1_wnf2v")
[node name="ColorRect" type="ColorRect" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
color = Color(0.638554, 0.499437, 0.164002, 0.384314)
[node name="TopLabel" type="Label" parent="."]
layout_mode = 0
offset_left = 25.0
offset_top = 17.0
offset_right = 125.0
offset_bottom = 40.0
text = "This is a test!"
label_settings = SubResource("LabelSettings_cnxo1")
[node name="Button" type="Button" parent="."]
layout_mode = 1
anchors_preset = 8
anchor_left = 0.5
anchor_top = 0.5
anchor_right = 0.5
anchor_bottom = 0.5
offset_left = -249.0
offset_top = -48.0
offset_right = 249.0
offset_bottom = 48.0
grow_horizontal = 2
grow_vertical = 2
theme_override_font_sizes/font_size = 64
text = "Press this button"
[node name="CountLabel" type="Label" parent="."]
layout_mode = 0
offset_left = 39.0
offset_top = 316.0
offset_right = 965.0
offset_bottom = 495.0
text = "The button has not been pressed."
label_settings = SubResource("LabelSettings_cnxo1")
horizontal_alignment = 1
autowrap_mode = 3
[node name="Cursor" type="ColorRect" parent="."]
process_mode = 4
material = SubResource("ShaderMaterial_84eui")
layout_mode = 0
offset_right = 32.0
offset_bottom = 32.0
mouse_filter = 2
[connection signal="pressed" from="Button" to="." method="_on_button_pressed"]
| |
118725
|
@tool
extends Area3D
############################################################################
# Water ripple effect shader - Bastiaan Olij
#
# This is an example of how to implement a more complex compute shader
# in Godot and making use of the new Custom Texture RD API added to
# the RenderingServer.
#
# If thread model is set to Multi-Threaded, the code related to compute will
# run on the render thread. This is needed as we want to add our logic to
# the normal rendering pipeline for this thread.
#
# The effect itself is an implementation of the classic ripple effect
# that has been around since the 90s, but in a compute shader.
# If someone knows if the original author ever published a paper I could
# quote, please let me know :)
@export var rain_size: float = 3.0
@export var mouse_size: float = 5.0
@export var texture_size: Vector2i = Vector2i(512, 512)
@export_range(1.0, 10.0, 0.1) var damp: float = 1.0
var t := 0.0
var max_t := 0.1
var texture: Texture2DRD
var next_texture: int = 0
var add_wave_point: Vector4
var mouse_pos: Vector2
var mouse_pressed: bool = false
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
# In case we're running stuff on the rendering thread
# we need to do our initialisation on that thread.
RenderingServer.call_on_render_thread(_initialize_compute_code.bind(texture_size))
# Get our texture from our material so we set our RID.
var material: ShaderMaterial = $MeshInstance3D.material_override
if material:
material.set_shader_parameter("effect_texture_size", texture_size)
# Get our texture object.
texture = material.get_shader_parameter("effect_texture")
func _exit_tree() -> void:
# Make sure we clean up!
if texture:
texture.texture_rd_rid = RID()
RenderingServer.call_on_render_thread(_free_compute_resources)
func _unhandled_input(event: InputEvent) -> void:
# If tool enabled, we don't want to handle our input in the editor.
if Engine.is_editor_hint():
return
if event is InputEventMouseMotion or event is InputEventMouseButton:
mouse_pos = event.global_position
if event is InputEventMouseButton and event.button_index == MouseButton.MOUSE_BUTTON_LEFT:
mouse_pressed = event.pressed
func _check_mouse_pos() -> void:
# This is a mouse event, do a raycast.
var camera := get_viewport().get_camera_3d()
var parameters := PhysicsRayQueryParameters3D.new()
parameters.from = camera.project_ray_origin(mouse_pos)
parameters.to = parameters.from + camera.project_ray_normal(mouse_pos) * 100.0
parameters.collision_mask = 1
parameters.collide_with_bodies = false
parameters.collide_with_areas = true
var result := get_world_3d().direct_space_state.intersect_ray(parameters)
if not result.is_empty():
# Transform our intersection point.
var pos: Vector3 = global_transform.affine_inverse() * result.position
add_wave_point.x = clamp(pos.x / 5.0, -0.5, 0.5) * texture_size.x + 0.5 * texture_size.x
add_wave_point.y = clamp(pos.z / 5.0, -0.5, 0.5) * texture_size.y + 0.5 * texture_size.y
# We have w left over so we use it to indicate mouse is over our water plane.
add_wave_point.w = 1.0
else:
add_wave_point.x = 0.0
add_wave_point.y = 0.0
add_wave_point.w = 0.0
func _process(delta: float) -> void:
# If tool is enabled, ignore mouse input.
if Engine.is_editor_hint():
add_wave_point.w = 0.0
else:
# Check where our mouse intersects our area, can change if things move.
_check_mouse_pos()
# If we're not using the mouse, animate water drops, we (ab)used our W for this.
if add_wave_point.w == 0.0:
t += delta
if t > max_t:
t = 0
add_wave_point.x = randi_range(0, texture_size.x)
add_wave_point.y = randi_range(0, texture_size.y)
add_wave_point.z = rain_size
else:
add_wave_point.z = 0.0
else:
add_wave_point.z = mouse_size if mouse_pressed else 0.0
# Increase our next texture index.
next_texture = (next_texture + 1) % 3
# Update our texture to show our next result (we are about to create).
# Note that `_initialize_compute_code` may not have run yet so the first
# frame this my be an empty RID.
if texture:
texture.texture_rd_rid = texture_rds[next_texture]
# While our render_process may run on the render thread it will run before our texture
# is used and thus our next_rd will be populated with our next result.
# It's probably overkill to sent texture_size and damp as parameters as these are static
# but we sent add_wave_point as it may be modified while process runs in parallel.
RenderingServer.call_on_render_thread(_render_process.bind(next_texture, add_wave_point, texture_size, damp))
###############################################################################
# Everything after this point is designed to run on our rendering thread.
var rd: RenderingDevice
var shader: RID
var pipeline: RID
# We use 3 textures:
# - One to render into
# - One that contains the last frame rendered
# - One for the frame before that
var texture_rds: Array[RID] = [RID(), RID(), RID()]
var texture_sets: Array[RID] = [RID(), RID(), RID()]
func _create_uniform_set(texture_rd: RID) -> RID:
var uniform := RDUniform.new()
uniform.uniform_type = RenderingDevice.UNIFORM_TYPE_IMAGE
uniform.binding = 0
uniform.add_id(texture_rd)
# Even though we're using 3 sets, they are identical, so we're kinda cheating.
return rd.uniform_set_create([uniform], shader, 0)
func _initialize_compute_code(init_with_texture_size: Vector2i) -> void:
# As this becomes part of our normal frame rendering,
# we use our main rendering device here.
rd = RenderingServer.get_rendering_device()
# Create our shader.
var shader_file := load("res://water_plane/water_compute.glsl")
var shader_spirv: RDShaderSPIRV = shader_file.get_spirv()
shader = rd.shader_create_from_spirv(shader_spirv)
pipeline = rd.compute_pipeline_create(shader)
# Create our textures to manage our wave.
var tf: RDTextureFormat = RDTextureFormat.new()
tf.format = RenderingDevice.DATA_FORMAT_R32_SFLOAT
tf.texture_type = RenderingDevice.TEXTURE_TYPE_2D
tf.width = init_with_texture_size.x
tf.height = init_with_texture_size.y
tf.depth = 1
tf.array_layers = 1
tf.mipmaps = 1
tf.usage_bits = (
RenderingDevice.TEXTURE_USAGE_SAMPLING_BIT |
RenderingDevice.TEXTURE_USAGE_COLOR_ATTACHMENT_BIT |
RenderingDevice.TEXTURE_USAGE_STORAGE_BIT |
RenderingDevice.TEXTURE_USAGE_CAN_UPDATE_BIT |
RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT
)
for i in 3:
# Create our texture.
texture_rds[i] = rd.texture_create(tf, RDTextureView.new(), [])
# Make sure our textures are cleared.
rd.texture_clear(texture_rds[i], Color(0, 0, 0, 0), 0, 1, 0, 1)
# Now create our uniform set so we can use these textures in our shader.
texture_sets[i] = _create_uniform_set(texture_rds[i])
| |
118727
|
shader_type spatial;
render_mode blend_mix, depth_draw_opaque, cull_back, diffuse_burley, specular_schlick_ggx;
uniform vec3 albedo : source_color;
uniform float metalic : hint_range(0.0, 1.0, 0.1) = 0.8;
uniform float roughness : hint_range(0.0, 1.0, 0.1) = 0.2;
uniform sampler2D effect_texture;
uniform vec2 effect_texture_size;
varying vec2 uv_tangent;
varying vec2 uv_binormal;
void vertex() {
vec2 pixel_size = vec2(1.0, 1.0) / effect_texture_size;
uv_tangent = UV + vec2(pixel_size.x, 0.0);
uv_binormal = UV + vec2(0.0, pixel_size.y);
}
void fragment() {
float f1 = texture(effect_texture, UV).r;
float f2 = texture(effect_texture, uv_tangent).r;
float f3 = texture(effect_texture, uv_binormal).r;
vec3 tangent = normalize(vec3(1.0, 0.0, f2 - f1));
vec3 binormal = normalize(vec3(0.0, 1.0, f3 - f1));
NORMAL_MAP = normalize(cross(binormal, tangent)) * 0.5 + 0.5;
ALBEDO = albedo.rgb;
METALLIC = metalic;
ROUGHNESS = roughness;
SPECULAR = 0.5;
}
| |
118742
|
[gd_scene load_steps=4 format=3 uid="uid://csyb8ij530w1l"]
[sub_resource type="StandardMaterial3D" id="1"]
diffuse_mode = 1
albedo_color = Color(0.149414, 0.796875, 0.569252, 1)
roughness = 0.0
[sub_resource type="BoxMesh" id="2"]
[sub_resource type="Environment" id="Environment_wokxq"]
ambient_light_source = 2
ambient_light_color = Color(0.305882, 0.360784, 0.537255, 1)
[node name="Node3D" type="Node3D"]
[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
transform = Transform3D(0.707107, 0, -0.707107, -0.353553, 0.866025, -0.353553, 0.612372, 0.5, 0.612372, 0, 0, 0)
material_override = SubResource("1")
mesh = SubResource("2")
[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
transform = Transform3D(0.926535, 0.11439, -0.358396, 0.199614, 0.658013, 0.726067, 0.318884, -0.744267, 0.586839, 0, 0, 0)
[node name="Camera3D" type="Camera3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2.08165e-12, 2.08165e-12, 3)
fov = 60.0
near = 0.1
[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
environment = SubResource("Environment_wokxq")
| |
118849
|
[node name="RichTextLabel" type="RichTextLabel" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 4/MarginContainer"]
layout_mode = 2
focus_mode = 2
bbcode_enabled = true
text = "[center]RichTextLabel: [color=#f88]Tab 4[/color] is selected.[/center]"
context_menu_enabled = true
selection_enabled = true
[node name="Tab 5" type="Control" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer"]
visible = false
layout_mode = 2
[node name="MarginContainer" type="MarginContainer" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 5"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 10
theme_override_constants/margin_top = 30
theme_override_constants/margin_right = 10
theme_override_constants/margin_bottom = 30
[node name="RichTextLabel" type="RichTextLabel" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 5/MarginContainer"]
layout_mode = 2
focus_mode = 2
bbcode_enabled = true
text = "[center]RichTextLabel: [color=#f8f]Tab 5[/color] is selected.[/center]"
context_menu_enabled = true
selection_enabled = true
[node name="Tab 6" type="Control" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer"]
visible = false
layout_mode = 2
[node name="MarginContainer" type="MarginContainer" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 6"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 10
theme_override_constants/margin_top = 30
theme_override_constants/margin_right = 10
theme_override_constants/margin_bottom = 30
[node name="RichTextLabel" type="RichTextLabel" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 6/MarginContainer"]
layout_mode = 2
focus_mode = 2
bbcode_enabled = true
text = "[center]RichTextLabel: [color=#b8f]Tab 6[/color] is selected.[/center]"
context_menu_enabled = true
selection_enabled = true
[node name="Tab 7" type="Control" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer"]
visible = false
layout_mode = 2
[node name="MarginContainer" type="MarginContainer" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 7"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 10
theme_override_constants/margin_top = 30
theme_override_constants/margin_right = 10
theme_override_constants/margin_bottom = 30
[node name="RichTextLabel" type="RichTextLabel" parent="MainPanel/HSplitContainer/BasicControls/VBoxContainer/TabContainer/Tab 7/MarginContainer"]
layout_mode = 2
focus_mode = 2
bbcode_enabled = true
text = "[center]RichTextLabel: [color=#fb6]Tab 7[/color] is selected.[/center]"
context_menu_enabled = true
selection_enabled = true
[node name="VSplitContainer" type="VSplitContainer" parent="MainPanel/HSplitContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_stretch_ratio = 2.0
theme_override_constants/separation = 0
theme_override_constants/minimum_grab_thickness = 24
[node name="Numbers" type="PanelContainer" parent="MainPanel/HSplitContainer/VSplitContainer"]
layout_mode = 2
theme_override_styles/panel = SubResource("StyleBoxFlat_bl4wp")
[node name="VBoxContainer" type="VBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers"]
layout_mode = 2
[node name="Title" type="Label" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 24
text = "Numbers"
horizontal_alignment = 1
[node name="SpinBox" type="SpinBox" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer"]
custom_minimum_size = Vector2(255, 0)
layout_mode = 2
size_flags_horizontal = 0
prefix = "SpinBox"
[node name="HSliderContainer" type="HBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="HSlider" type="HSlider" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/HSliderContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_stretch_ratio = 0.5
value = 50.0
[node name="Label" type="Label" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/HSliderContainer"]
layout_mode = 2
size_flags_horizontal = 3
text = "HSlider"
[node name="ProgressBarContainer" type="HBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="ProgressBar" type="ProgressBar" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/ProgressBarContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_stretch_ratio = 0.5
value = 50.0
[node name="Label" type="Label" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/ProgressBarContainer"]
layout_mode = 2
size_flags_horizontal = 3
text = "ProgressBar"
[node name="HSeparatorContainer" type="HBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer"]
layout_mode = 2
[node name="HSeparatorLeft" type="HSeparator" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/HSeparatorContainer"]
layout_mode = 2
size_flags_horizontal = 3
[node name="Label" type="Label" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/HSeparatorContainer"]
layout_mode = 2
text = "HSeparator"
[node name="HSeparatorRight" type="HSeparator" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/HSeparatorContainer"]
layout_mode = 2
size_flags_horizontal = 3
[node name="TextureProgressContainer" type="HBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer"]
layout_mode = 2
[node name="Control" type="Control" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/TextureProgressContainer"]
custom_minimum_size = Vector2(64, 64)
layout_mode = 2
[node name="TextureProgressBar" type="TextureProgressBar" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/TextureProgressContainer/Control"]
layout_mode = 0
offset_right = 128.0
offset_bottom = 128.0
scale = Vector2(0.5, 0.5)
value = 67.0
fill_mode = 4
texture_progress = ExtResource("1_8tycj")
[node name="Label" type="Label" parent="MainPanel/HSplitContainer/VSplitContainer/Numbers/VBoxContainer/TextureProgressContainer"]
layout_mode = 2
text = "TextureProgressBar"
[node name="Lists" type="PanelContainer" parent="MainPanel/HSplitContainer/VSplitContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
size_flags_stretch_ratio = 2.5
theme_override_styles/panel = SubResource("StyleBoxFlat_bl4wp")
[node name="VBoxContainer" type="VBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Lists"]
layout_mode = 2
[node name="Title" type="Label" parent="MainPanel/HSplitContainer/VSplitContainer/Lists/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 24
text = "Lists"
horizontal_alignment = 1
[node name="HBoxContainer" type="HBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Lists/VBoxContainer"]
layout_mode = 2
size_flags_vertical = 3
theme_override_constants/separation = 10
[node name="VBoxContainer" type="VBoxContainer" parent="MainPanel/HSplitContainer/VSplitContainer/Lists/VBoxContainer/HBoxContainer"]
layout_mode = 2
size_flags_horizontal = 3
| |
118859
|
extends ColorPickerButton
# Returns the data to pass from an object when you click and drag away from
# this object. Also calls `set_drag_preview()` to show the mouse dragging
# something so the user knows that the operation is working.
func _get_drag_data(_at_position: Vector2) -> Color:
# Use another colorpicker as drag preview.
var cpb := ColorPickerButton.new()
cpb.color = color
cpb.size = Vector2(80.0, 50.0)
# Allows us to center the color picker on the mouse.
var preview := Control.new()
preview.add_child(cpb)
cpb.position = -0.5 * cpb.size
# Sets what the user will see they are dragging.
set_drag_preview(preview)
# Return color as drag data.
return color
# Returns a boolean by examining the data being dragged to see if it's valid
# to drop here.
func _can_drop_data(_at_position: Vector2, data: Variant) -> bool:
return typeof(data) == TYPE_COLOR
# Takes the data being dragged and processes it. In this case, we are
# assigning a new color to the target color picker button.
func _drop_data(_at_position: Vector2, data: Variant) -> void:
color = data
| |
118864
|
# The root Control node ("Main") and AspectRatioContainer nodes are the most important
# pieces of this demo.
# Both nodes have their Layout set to Full Rect
# (with their rect spread across the whole viewport, and Anchor set to Full Rect).
extends Control
var base_window_size := Vector2(
ProjectSettings.get_setting("display/window/size/viewport_width"),
ProjectSettings.get_setting("display/window/size/viewport_height")
)
# These defaults match this demo's project settings. Adjust as needed if adapting this
# in your own project.
var stretch_mode := Window.CONTENT_SCALE_MODE_CANVAS_ITEMS
var stretch_aspect := Window.CONTENT_SCALE_ASPECT_EXPAND
var scale_factor := 1.0
var gui_aspect_ratio := -1.0
var gui_margin := 0.0
@onready var panel: Panel = $Panel
@onready var arc: AspectRatioContainer = $Panel/AspectRatioContainer
func _ready() -> void:
# The `resized` signal will be emitted when the window size changes, as the root Control node
# is resized whenever the window size changes. This is because the root Control node
# uses a Full Rect anchor, so its size will always be equal to the window size.
resized.connect(_on_resized)
update_container.call_deferred()
func update_container() -> void:
# The code within this function needs to be run deferred to work around an issue with containers
# having a 1-frame delay with updates.
# Otherwise, `panel.size` returns a value of the previous frame, which results in incorrect
# sizing of the inner AspectRatioContainer when using the Fit to Window setting.
for _i in 2:
if is_equal_approx(gui_aspect_ratio, -1.0):
# Fit to Window. Tell the AspectRatioContainer to use the same aspect ratio as the window,
# making the AspectRatioContainer not have any visible effect.
arc.ratio = panel.size.aspect()
# Apply GUI offset on the AspectRatioContainer's parent (Panel).
# This also makes the GUI offset apply on controls located outside the AspectRatioContainer
# (such as the inner side label in this demo).
panel.offset_top = gui_margin
panel.offset_bottom = -gui_margin
else:
# Constrained aspect ratio.
arc.ratio = min(panel.size.aspect(), gui_aspect_ratio)
# Adjust top and bottom offsets relative to the aspect ratio when it's constrained.
# This ensures that GUI offset settings behave exactly as if the window had the
# original aspect ratio size.
panel.offset_top = gui_margin / gui_aspect_ratio
panel.offset_bottom = -gui_margin / gui_aspect_ratio
panel.offset_left = gui_margin
panel.offset_right = -gui_margin
func _on_gui_aspect_ratio_item_selected(index: int) -> void:
match index:
0: # Fit to Window
gui_aspect_ratio = -1.0
1: # 5:4
gui_aspect_ratio = 5.0 / 4.0
2: # 4:3
gui_aspect_ratio = 4.0 / 3.0
3: # 3:2
gui_aspect_ratio = 3.0 / 2.0
4: # 16:10
gui_aspect_ratio = 16.0 / 10.0
5: # 16:9
gui_aspect_ratio = 16.0 / 9.0
6: # 21:9
gui_aspect_ratio = 21.0 / 9.0
update_container.call_deferred()
func _on_resized() -> void:
update_container.call_deferred()
func _on_gui_margin_drag_ended(_value_changed: bool) -> void:
gui_margin = $"Panel/AspectRatioContainer/Panel/CenterContainer/Options/GUIMargin/HSlider".value
$"Panel/AspectRatioContainer/Panel/CenterContainer/Options/GUIMargin/Value".text = str(gui_margin)
update_container.call_deferred()
func _on_window_base_size_item_selected(index: int) -> void:
match index:
0: # 648×648 (1:1)
base_window_size = Vector2(648, 648)
1: # 640×480 (4:3)
base_window_size = Vector2(640, 480)
2: # 720×480 (3:2)
base_window_size = Vector2(720, 480)
3: # 800×600 (4:3)
base_window_size = Vector2(800, 600)
4: # 1152×648 (16:9)
base_window_size = Vector2(1152, 648)
5: # 1280×720 (16:9)
base_window_size = Vector2(1280, 720)
6: # 1280×800 (16:10)
base_window_size = Vector2(1280, 800)
7: # 1680×720 (21:9)
base_window_size = Vector2(1680, 720)
get_viewport().content_scale_size = base_window_size
update_container.call_deferred()
func _on_window_stretch_mode_item_selected(index: int) -> void:
stretch_mode = index as Window.ContentScaleMode
get_viewport().content_scale_mode = stretch_mode
# Disable irrelevant options when the stretch mode is Disabled.
$"Panel/AspectRatioContainer/Panel/CenterContainer/Options/WindowBaseSize/OptionButton".disabled = stretch_mode == Window.CONTENT_SCALE_MODE_DISABLED
$"Panel/AspectRatioContainer/Panel/CenterContainer/Options/WindowStretchAspect/OptionButton".disabled = stretch_mode == Window.CONTENT_SCALE_MODE_DISABLED
func _on_window_stretch_aspect_item_selected(index: int) -> void:
stretch_aspect = index as Window.ContentScaleAspect
get_viewport().content_scale_aspect = stretch_aspect
func _on_window_scale_factor_drag_ended(_value_changed: bool) -> void:
scale_factor = $"Panel/AspectRatioContainer/Panel/CenterContainer/Options/WindowScaleFactor/HSlider".value
$"Panel/AspectRatioContainer/Panel/CenterContainer/Options/WindowScaleFactor/Value".text = "%d%%" % (scale_factor * 100)
get_viewport().content_scale_factor = scale_factor
func _on_window_stretch_scale_mode_item_selected(index: int) -> void:
get_viewport().content_scale_stretch = index
| |
118865
|
# Multiple Resolutions and Aspect Ratios
**Note:** This demo is intended to showcase what Godot can do in terms of
supporting multiple resolutions and aspect ratios. As such, this demo very
full-featured but it's also fairly complex to understand.
If you're in a hurry and want to implement *decent* support for multiple
resolutions and aspect ratios in your game, see [Multiple resolutions crash
course](#multiple-resolutions-crash-course).
___
This project demonstrates how to set up a project to handle screens of multiple
resolutions and aspect ratios.
This demo allows you to adjust the window's base resolution, stretch mode,
stretch aspect, and scale factor (internally known as "stretch shrink"). This
lets you see what happens when adjusting those properties. Make sure to resize
the project window in any direction to see the difference with the various
stretch mode and stretch aspect settings.
The GUI can be made to fit the window or constrained to a specific aspect ratio
from a list of common aspect ratios. On ultrawide aspect ratios, this can be
used to prevent HUD elements from being too spread apart, which can harm the
gameplay experience. For non-essential HUD elements, specific controls can be
made to ignore this aspect ratio constraint when it makes sense (e.g. a list of
players on the side of the screen).
Additionally, a GUI margin setting is provided to better handle TVs with an
overscan area to prevent GUI elements from being cut off. This can also improve
the gameplay experience on large monitors by bringing HUD elements closer to the
center of the screen.
A DynamicFont with multichannel signed distance field (MSDF) rendering is also used.
This allows for crisp font rendering at any resolution, without having to re-rasterize
the font when the font size changes. This makes changing the various settings in this
demo faster, especially when large font sizes are used as a result of the GUI scale factor
setting being increased.
Note that by default, Godot uses font oversampling for traditional rasterized
DynamicFonts. This means MSDF fonts are *not* required to have crisp fonts at
higher-than-default screen resolutions.
Language: GDScript
Renderer: Compatibility
Check out this demo on the asset library: https://godotengine.org/asset-library/asset/2771
## Technical notes
The demo works with the following project settings:
- `canvas_items` stretch mode (this was called `2d` in Godot 3.x).
Recommended for most non-pixel art games.
- `expand` stretch aspect (allows support for multiple aspect ratios without
distortion or black bars).
- Using a base window size with a 1:1 aspect ratio (`648×648` in this demo).
This prevents GUI elements from automatically shrinking, even in portrait
mode.
- With this setting, to prevent the GUI from breaking at narrow aspect ratios,
the GUI must be designed to work with a 1:1 aspect ratio. This is not
feasible in most complex games, so a base window size with a wider aspect
ratio (such as 4:3 or 16:10) can be used instead. The wider the aspect
ratio, the easier design becomes, but the GUI will automatically become
smaller at narrow aspect ratios unless the user overrides its scale with the
stretch shrink setting. Many devices such as the Steam Deck and MacBooks
feature 16:10 displays, so it's recommended to use a 16:10 resolution or
narrower as a base window size to ensure a good gameplay experience out of
the box on those devices.
- Using a window size override with a 16:9 aspect ratio (`1152×648` in this demo).
This way, the project starts in a 16:9 window even if the base window size has
a 1:1 aspect ratio.
- The test window height matches the width and height of the base window size,
so GUI elements are still at the same size.
## Multiple resolutions crash course
**Not everything in this demo is critical to all games.** For gamejam projects or mobile games, most of this can be skipped.
See the [Common use case scenarios](https://docs.godotengine.org/en/stable/tutorials/rendering/multiple_resolutions.html#common-use-case-scenarios)
section in the Multiple resolutions documentation.
With the simpler setup described in the above documentation, there are a few
limitations compared to this demo:
- The HUD will shrink when the aspect ratio becomes narrower than the base
window size. As such, it's recommended to use a base window size with a 16:10
aspect ratio to prevent the HUD from shrinking on Steam Deck and MacBooks.
- Players will not be able to define a margin, which can be problematic when
playing on a TV (as overscan can obstruct some HUD elements). This can be
worked around by ensuring the entire HUD always has a small margin around it.
This can be done by increasing the Margin properties on all sides on the root
Control node by 10-30 pixels or so.
If you're releasing a full-fledged game on a desktop platform such as Steam,
consider implementing full support as this demo suggests. Your players will
thank you :slightly_smiling_face:
## Screenshots

| |
118867
|
; Engine configuration file.
; It's best edited using the editor UI and not directly,
; since the parameters that go here are not all obvious.
;
; Format:
; [section] ; section goes between []
; param=value ; assign values to parameters
config_version=5
[application]
config/name="Multiple Resolutions and Aspect Ratios"
config/description="This project demonstrates how to set up a project to handle screens of
multiple resolutions and aspect ratios.
The GUI can be made to fit the window or constrained to a specific
aspect ratio from a list of common aspect ratios. On ultrawide aspect ratios,
this can be used to prevent HUD elements from being too spread apart,
which can harm the gameplay experience.
For non-essential HUD elements, specific controls can be made to
ignore this aspect ratio constraint when it makes sense
(e.g. a list of players on the side of the screen).
Additionally, a GUI margin setting is provided to better handle TVs
with an overscan area to prevent GUI elements from being cut off.
This can also improve the gameplay experience on large monitors
by bringing HUD elements closer to the center of the screen."
config/tags=PackedStringArray("accessibility", "best_practices", "demo", "gui", "official")
run/main_scene="res://main.tscn"
config/features=PackedStringArray("4.2")
run/low_processor_mode=true
config/icon="res://icon.webp"
[debug]
gdscript/warnings/untyped_declaration=1
[display]
window/size/viewport_width=648
window/size/window_width_override=1152
window/size/window_height_override=648
window/stretch/mode="canvas_items"
window/stretch/aspect="expand"
window/handheld/orientation="sensor"
[gui]
theme/default_font_multichannel_signed_distance_field=true
[rendering]
renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility"
environment/defaults/default_clear_color=Color(0.133333, 0.133333, 0.2, 1)
| |
118890
|
[gd_scene load_steps=4 format=2]
[ext_resource path="res://ball.png" type="Texture2D" id=1]
[ext_resource path="res://logic/Ball.cs" type="Script" id=2]
[sub_resource type="CircleShape2D" id=1]
radius = 4.65663
[node name="Ball" type="Area2D"]
script = ExtResource( 2 )
[node name="Sprite2D" type="Sprite2D" parent="."]
texture = ExtResource( 1 )
[node name="CollisionShape2D" type="CollisionShape2D" parent="."]
shape = SubResource( 1 )
| |
118909
|
[gd_scene load_steps=12 format=3 uid="uid://bufr8nynnqrj"]
[ext_resource type="Script" path="res://Logic/Paddle.cs" id="1"]
[ext_resource type="Texture2D" uid="uid://cgbjbhglgxf0k" path="res://paddle.png" id="2"]
[ext_resource type="Script" path="res://Logic/Ball.cs" id="4"]
[ext_resource type="Texture2D" uid="uid://13ht46tyr4ae" path="res://ball.png" id="5"]
[ext_resource type="Texture2D" uid="uid://cim6es185kfto" path="res://separator.png" id="6"]
[ext_resource type="Script" path="res://Logic/Wall.cs" id="7"]
[ext_resource type="Script" path="res://Logic/CeilingFloor.cs" id="8"]
[sub_resource type="RectangleShape2D" id="1"]
size = Vector2(4, 16)
[sub_resource type="RectangleShape2D" id="2"]
size = Vector2(4, 4)
[sub_resource type="RectangleShape2D" id="3"]
size = Vector2(10, 200)
[sub_resource type="RectangleShape2D" id="4"]
size = Vector2(320, 10)
[node name="Pong" type="Node2D"]
[node name="Background" type="ColorRect" parent="."]
offset_right = 640.0
offset_bottom = 400.0
color = Color(0.141176, 0.152941, 0.164706, 1)
[node name="Left" type="Area2D" parent="."]
modulate = Color(0, 1, 1, 1)
position = Vector2(67.6285, 192.594)
script = ExtResource("1")
[node name="Sprite2D" type="Sprite2D" parent="Left"]
texture = ExtResource("2")
[node name="Collision" type="CollisionShape2D" parent="Left"]
shape = SubResource("1")
[node name="Right" type="Area2D" parent="."]
modulate = Color(1, 0, 1, 1)
position = Vector2(563.815, 188.919)
script = ExtResource("1")
[node name="Sprite2D" type="Sprite2D" parent="Right"]
texture = ExtResource("2")
[node name="Collision" type="CollisionShape2D" parent="Right"]
shape = SubResource("1")
[node name="Ball" type="Area2D" parent="."]
position = Vector2(320.5, 191.124)
script = ExtResource("4")
[node name="Sprite2D" type="Sprite2D" parent="Ball"]
texture = ExtResource("5")
[node name="Collision" type="CollisionShape2D" parent="Ball"]
shape = SubResource("2")
[node name="Separator" type="Sprite2D" parent="."]
position = Vector2(320, 200)
texture = ExtResource("6")
[node name="Node2D" type="Node2D" parent="."]
[node name="LeftWall" type="Area2D" parent="."]
position = Vector2(-10, 200)
script = ExtResource("7")
[node name="Collision" type="CollisionShape2D" parent="LeftWall"]
shape = SubResource("3")
[node name="RightWall" type="Area2D" parent="."]
position = Vector2(650, 200)
script = ExtResource("7")
[node name="Collision" type="CollisionShape2D" parent="RightWall"]
shape = SubResource("3")
[node name="Ceiling" type="Area2D" parent="."]
position = Vector2(320, -10)
script = ExtResource("8")
[node name="Collision" type="CollisionShape2D" parent="Ceiling"]
shape = SubResource("4")
[node name="Floor" type="Area2D" parent="."]
position = Vector2(320, 410)
script = ExtResource("8")
_bounceDirection = -1
[node name="Collision" type="CollisionShape2D" parent="Floor"]
shape = SubResource("4")
[connection signal="area_entered" from="Left" to="Left" method="OnAreaEntered"]
[connection signal="area_entered" from="Right" to="Right" method="OnAreaEntered"]
[connection signal="area_entered" from="LeftWall" to="LeftWall" method="OnWallAreaEntered"]
[connection signal="area_entered" from="RightWall" to="RightWall" method="OnWallAreaEntered"]
[connection signal="area_entered" from="Ceiling" to="Ceiling" method="OnAreaEntered"]
[connection signal="area_entered" from="Floor" to="Floor" method="OnAreaEntered"]
| |
118931
|
@tool
extends Control
var zoom_level := 0
var is_panning = false
var pan_center: Vector2
var viewport_center: Vector2
var view_mode_index := 0
var editor_interface: EditorInterface # Set in node25d_plugin.gd
var moving = false
@onready var viewport_2d = $Viewport2D
@onready var viewport_overlay = $ViewportOverlay
@onready var view_mode_button_group: ButtonGroup = $"../TopBar/ViewModeButtons/45Degree".group
@onready var zoom_label: Label = $"../TopBar/Zoom/ZoomPercent"
@onready var gizmo_25d_scene = preload("res://addons/node25d-cs/main_screen/gizmo_25d.tscn")
func _ready():
# Give Godot a chance to fully load the scene. Should take two frames.
await get_tree().process_frame
await get_tree().process_frame
var edited_scene_root = get_tree().edited_scene_root
if not edited_scene_root:
# Godot hasn't finished loading yet, so try loading the plugin again.
editor_interface.set_plugin_enabled("node25d", false)
editor_interface.set_plugin_enabled("node25d", true)
return
# Alright, we're loaded up. Now check if we have a valid world and assign it.
var world_2d = edited_scene_root.get_viewport().world_2d
if world_2d == get_viewport().world_2d:
return # This is the MainScreen25D scene opened in the editor!
viewport_2d.world_2d = world_2d
func _process(delta):
if not editor_interface: # Something's not right... bail!
return
# View mode polling.
var view_mode_changed_this_frame = false
var new_view_mode = view_mode_button_group.get_pressed_button().get_index()
if view_mode_index != new_view_mode:
view_mode_index = new_view_mode
view_mode_changed_this_frame = true
_recursive_change_view_mode(get_tree().edited_scene_root)
# Zooming.
if Input.is_mouse_button_pressed(MOUSE_BUTTON_WHEEL_UP):
zoom_level += 1
elif Input.is_mouse_button_pressed(MOUSE_BUTTON_WHEEL_DOWN):
zoom_level -= 1
var zoom = _get_zoom_amount()
# SubViewport size.
var size = get_global_rect().size
viewport_2d.size = size
# SubViewport transform.
var viewport_trans = Transform2D.IDENTITY
viewport_trans.x *= zoom
viewport_trans.y *= zoom
viewport_trans.origin = viewport_trans.basis_xform(viewport_center) + size / 2
viewport_2d.canvas_transform = viewport_trans
viewport_overlay.canvas_transform = viewport_trans
# Delete unused gizmos.
var selection = editor_interface.get_selection().get_selected_nodes()
var overlay_children = viewport_overlay.get_children()
for overlay_child in overlay_children:
var contains = false
for selected in selection:
if selected == overlay_child.get("node25d") and not view_mode_changed_this_frame:
contains = true
if not contains:
overlay_child.queue_free()
# Add new gizmos.
for selected in selection:
if selected.has_method("Node25DReady"):
var new = true
for overlay_child in overlay_children:
if selected == overlay_child.get("node25d"):
new = false
if new:
var gizmo = gizmo_25d_scene.instantiate()
viewport_overlay.add_child(gizmo)
gizmo.set("node25d", selected)
gizmo.call("Initialize")
# This only accepts input when the mouse is inside of the 2.5D viewport.
func _gui_input(event):
if event is InputEventMouseButton:
if event.is_pressed():
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
zoom_level += 1
accept_event()
elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
zoom_level -= 1
accept_event()
elif event.button_index == MOUSE_BUTTON_MIDDLE:
is_panning = true
pan_center = viewport_center - event.position
accept_event()
elif event.button_index == MOUSE_BUTTON_LEFT:
var overlay_children = viewport_overlay.get_children()
for overlay_child in overlay_children:
overlay_child.set("wantsToMove", true)
accept_event()
elif event.button_index == MOUSE_BUTTON_MIDDLE:
is_panning = false
accept_event()
elif event.button_index == MOUSE_BUTTON_LEFT:
var overlay_children = viewport_overlay.get_children()
for overlay_child in overlay_children:
overlay_child.set("wantsToMove", false)
accept_event()
elif event is InputEventMouseMotion:
if is_panning:
viewport_center = pan_center + event.position
accept_event()
func _recursive_change_view_mode(current_node):
if current_node.has_method("set_view_mode"):
current_node.set_view_mode(view_mode_index) # GDScript.
if current_node.has_method("SetViewMode"):
current_node.call("SetViewMode", view_mode_index) # C#.
for child in current_node.get_children():
_recursive_change_view_mode(child)
func _get_zoom_amount():
var zoom_amount = pow(1.05476607648, zoom_level) # 13th root of 2.
zoom_label.text = str(round(zoom_amount * 1000) / 10) + "%"
return zoom_amount
func _on_ZoomOut_pressed():
zoom_level -= 1
func _on_ZoomIn_pressed():
zoom_level += 1
func _on_ZoomReset_pressed():
zoom_level = 0
| |
118959
|
[gd_scene load_steps=7 format=2]
[ext_resource path="res://addons/node25d-cs/Node25D.cs" type="Script" id=1]
[ext_resource path="res://addons/node25d-cs/icons/node_25d_icon.png" type="Texture2D" id=2]
[ext_resource path="res://assets/player/PlayerMath25D.cs" type="Script" id=3]
[ext_resource path="res://assets/player/textures/stand.png" type="Texture2D" id=4]
[ext_resource path="res://assets/player/PlayerSprite.cs" type="Script" id=5]
[sub_resource type="BoxShape3D" id=1]
extents = Vector3(0.5, 1, 0.5)
[node name="Player25D" type="Node2D"]
position = Vector2(0, -226.274)
z_index = 100
script = ExtResource( 1 )
__meta__ = {
"_editor_icon": ExtResource( 2 )
}
spatialPosition = Vector3(0, 10, 0)
[node name="PlayerMath25D" type="CharacterBody3D" parent="."]
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 10, 0)
script = ExtResource( 3 )
[node name="CollisionShape3D" type="CollisionShape3D" parent="PlayerMath25D"]
shape = SubResource( 1 )
__meta__ = {
"_edit_lock_": true
}
[node name="PlayerSprite" type="Sprite2D" parent="."]
scale = Vector2(1, 0.75)
z_index = 1
texture = ExtResource( 4 )
vframes = 5
script = ExtResource( 5 )
[node name="PlayerCamera" type="Camera2D" parent="PlayerSprite"]
current = true
| |
119002
|
extends Game
func _ready() -> void:
var player_2 := %Player2 as Player
var viewport_1 := %Viewport1 as SubViewport
var viewport_2 := %Viewport2 as SubViewport
viewport_2.world_2d = viewport_1.world_2d
player_2.camera.custom_viewport = viewport_2
player_2.camera.make_current()
| |
119066
|
[gd_resource type="ShaderMaterial" load_steps=2 format=3 uid="uid://djwm5nol3d801"]
[sub_resource type="Shader" id="1"]
code = "// original wind shader from https://github.com/Maujoe/godot-simple-wind-shader-2d/tree/master/assets/maujoe.simple_wind_shader_2d
// original script modified by HungryProton so that the assets are moving differently : https://pastebin.com/VL3AfV8D
//
// speed - The speed of the wind movement.
// minStrength - The minimal strength of the wind movement.
// maxStrength - The maximal strength of the wind movement.
// strengthScale - Scalefactor for the wind strength.
// interval - The time between minimal and maximal strength changes.
// detail - The detail (number of waves) of the wind movement.
// distortion - The strength of geometry distortion.
// heightOffset - The height where the wind begins to move. By default 0.0.
shader_type canvas_item;
render_mode blend_mix;
// Wind settings.
uniform float speed = 1.0;
uniform float minStrength : hint_range(0.0, 1.0) = 0.05;
uniform float maxStrength : hint_range(0.0, 1.0) = 0.01;
uniform float strengthScale = 100.0;
uniform float interval = 3.5;
uniform float detail = 1.0;
uniform float distortion : hint_range(0.0, 1.0);
uniform float heightOffset : hint_range(0.0, 1.0);
// With the offset value, you can if you want different moves for each asset. Just put a random value (1, 2, 3) in the editor. Don't forget to mark the material as unique if you use this
uniform float offset = 0;
float getWind(vec2 vertex, vec2 uv, float time){
float diff = pow(maxStrength - minStrength, 2.0);
float strength = clamp(minStrength + diff + sin(time / interval) * diff, minStrength, maxStrength) * strengthScale;
float wind = (sin(time) + cos(time * detail)) * strength * max(0.0, (1.0-uv.y) - heightOffset);
return wind;
}
void vertex() {
vec4 pos = MODEL_MATRIX * vec4(0.0, 0.0, 0.0, 1.0);
float time = TIME * speed + offset;
//float time = TIME * speed + pos.x * pos.y ; not working when moving...
VERTEX.x += getWind(VERTEX.xy, UV, time);
}"
[resource]
shader = SubResource("1")
shader_parameter/speed = 1.0
shader_parameter/minStrength = 0.05
shader_parameter/maxStrength = 0.01
shader_parameter/strengthScale = 100.0
shader_parameter/interval = 3.5
shader_parameter/detail = 1.0
shader_parameter/distortion = null
shader_parameter/heightOffset = null
shader_parameter/offset = 0.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.